2014-04-16 39 views
0

我有以下的代碼這在他們行有一定的價值MySQL的結果數組:如何創建

<?php 
include_once 'init/init.funcs.php'; 
$pollid=$_GET['pollid']; 
$result = mysql_query('SELECT question FROM questions where survey_id="' . $pollid . '"'); 
$question = mysql_result($result, 0); 
echo $pollid; 
echo $question; 

?> 

它將回音具有survey_id = $ pollid的第一個問題。但是我想編制一系列所有問題,其中survey_id = $ pollid.How我可以這樣做嗎?

+0

嚴重:| mysql_result!的 – h2O

+0

可能重複[如何獲取結果在PHP的MySQL的所有行?](http://stackoverflow.com/questions/10940332/how-to-fetch-all-the-row-of-the-result-在-PHP-MySQL的) – mario

回答

1

通過的結果只是循環,並將其添加到一個數組:

$pollid = (int) $_GET['pollid']; 
$questions = array(); 
$result = mysql_query('SELECT question FROM questions where survey_id="' . $pollid . '"'); 
while($row = mysql_fetch_assoc($result)) { 
    $questions[$pollid] = $row['question ']; 
} 

Please, don't use mysql_* functions in new code。他們不再維護and are officially deprecated。請參閱​​?請改爲了解prepared statements,並使用PDOMySQLi - this article將幫助您決定哪個。如果您選擇PDO,here is a good tutorial

您也可以開放至SQL injections。在我的例子中,我鑄造了$_GET['pollid']爲一個整數,以幫助防止它們。更好的方法是使用上面提到的準備好的語句。

0

嘗試使用mysqli_而不是mysql_,

// MYSQLI 
$mysqli = new mysqli('localhost', 'example', 'example', 'test'); 

print '<h3>MYSQLI: simple select</h3>'; 
$rs = $mysqli->query(YOUR SELECT QUERY); 
while($row = $rs->fetch_object()) 
{ 
    //DATA 
}