2014-10-17 47 views
3

好的。將PHP變量傳遞到mysql_query字符串中有點複雜的問題。在mysql_query字符串中使用PHP變量

$ _GET ['date'];當通過將包含類似:2015_01_07_1

我需要使用$周變量傳遞到表名稱的GET數據。

<?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); 
    ?> 
+0

我知道這是變量拋出錯誤,因爲在sql編輯器中通過phpmyadmin使用查詢,它與2015_01_07_1而不是變量正常工作。 – 2014-10-17 16:27:19

+0

只是刪除「$ week''周圍的單引號,並使用大括號應該是'games_brixx_gastonia _ {$ week} .rank'。在你的情況下不需要大括號,但確保你不會混淆更復雜的變量是一個好習慣。 – bansi 2014-10-17 16:31:09

回答

3

更改字符串文本:

"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" 

您必須刪除'字符; 這是去分貝爲games_brixx_gastonia_'2015_01_07_1'.rank

+0

太棒了!非常感謝。我知道這很簡單,我只是俯視它。 – 2014-10-17 16:29:12

+0

接受的答案標記,將不勝感激:) – 2014-10-17 16:29:52

+0

另外,我也看到了我在語法顯示players.email的其他錯誤。它應該說players_brixx_gastonia.email – 2014-10-17 16:31:15

1

爲什麼你把單引號?它應該工作:

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 

無論如何,我寧願建議你使用語句來代替。檢查出來: http://php.net/manual/pt_BR/mysqli.prepare.php

+0

+1用於推薦準備好的語句。 – bansi 2014-10-17 16:44:32

+0

是的。我想這對於代碼可讀性甚至是有用的,並且希望能夠與SQL注入作鬥爭。 – 2014-10-17 17:30:14

0

只需刪除'個字符。否則,查詢將嘗試從表games_brixx_gastonia_'2015_01_07_1'而不是games_brixx_gastonia_2015_01_07_1獲取數據。