我有以下代码:
<?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的所有问题的数组。我能做到这一点吗?
答案 0 :(得分: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。请参阅red box?转而了解prepared statements,并使用PDO或MySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial。
您也对SQL injections 持开放态度。在我的示例中,我将$_GET['pollid']
转换为整数以帮助防范它们。更好的方法是使用上面提到的准备好的陈述。
答案 1 :(得分: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
}