我有以下代码:
<?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 的所有问题的数组。我该怎么做?
最佳答案
只需循环结果并将它们添加到数组中:
$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']
转换为整数以帮助防止它们。更好的方法是使用上面提到的准备好的语句。
关于php - 如何创建在其行中具有特定值的mysql结果数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23112551/