简体   繁体   中英

Using PHP variable in mysql_query string

OK guys. I have a somewhat complicated issue with passing PHP variables into the mysql_query string.

The $_GET['date']; when passed will contain something like: 2015_01_07_1

I need to have the GET data passed into the table names using the $week variables.

<?php

    $week= $_GET['date'];

    $con=mysqli_connect("localhost","root","mypassword","beerhandpoker");
    // Check connection
        if (mysqli_connect_errno()) {
          echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }

    $result = mysqli_query
    ($con,
        "SELECT games_brixx_gastonia_'$week'.rank, players_brixx_gastonia.name, games_brixx_gastonia_'$week'.points
        FROM games_brixx_gastonia_'$week', players_brixx_gastonia
        WHERE games_brixx_gastonia_'$week'.email = players.email
        ORDER BY games_brixx_gastonia_'$week'.rank
        LIMIT 20"
    );

    echo "<table>
        <tr>
        <th>Rank</th>
        <th>Name</th>
        <th>Points</th>
        </tr>";

    while($row = mysqli_fetch_array($result)) {
        echo "<tr>";
        echo "<td>" . $row['rank'] . "</td>";
        echo "<td>" . $row['name'] . "</td>";
        echo "<td>" . $row['points'] . "</td>";
        echo "</tr>";
    }

    echo "</table>";

    mysqli_close($con);
    ?>

Change the string literal to:

"SELECT games_brixx_gastonia_$week.rank,    
players_brixx_gastonia.name,games_brixx_gastonia_$week.points
FROM games_brixx_gastonia_$week, players_brixx_gastonia
WHERE games_brixx_gastonia_$week.email = players_brixx_gastonia.email
ORDER BY games_brixx_gastonia_$week.rank
LIMIT 20"

You have to remove the ' characters; It's going to the db as games_brixx_gastonia_'2015_01_07_1'.rank

Why do you put single quotes? It should work:

SELECT games_brixx_gastonia_{$week}.rank, players_brixx_gastonia.name, games_brixx_gastonia_{$week}.points
FROM games_brixx_gastonia_{$week}, players_brixx_gastonia
WHERE games_brixx_gastonia_{$week}.email = players.email
ORDER BY games_brixx_gastonia_{$week}.rank
LIMIT 20

Anyway, I'd rather advice you to use statement instead. Check it out: http://php.net/manual/pt_BR/mysqli.prepare.php

Just remove the ' characters. Otherwise the query would try to get data from the table games_brixx_gastonia_'2015_01_07_1' and not games_brixx_gastonia_2015_01_07_1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM