1

我对以下代码有几个问题......基本上,需要将几个值存储在$sqlBAnswer中,但如果我只是将[]放在它之后,它会保存值"Array"

//Find the answer given by the user to the last answered question
$sqlB = mysql_query("SELECT Answer FROM Responses WHERE User = $sqlAPKID");
//If the operation produces an error, output an error message
if (!$sqlB) {
    die('Invalid query for SQLB: ' . mysql_error());
}
//Count the number of rows output
$sqlBCount = mysql_num_rows($sqlB);
//If rows exist, define the values
if ($sqlBCount > 0) {
    while ($row = mysql_fetch_array($sqlB)) {
        $sqlBAnswer = $row["Answer"];
    }
}

假设$sqlBAnswer确实设法保存了多个值,那么我需要执行另一个查询,该查询将只产生一个值(即只有一个存储在$sqlBAnswer中的值会在结果集中。

我计划使用围绕以下代码的foreach循环来执行此操作:

//Find the number of the next question to be answered based on the user's previous answer and the question they answered
$sqlC = mysql_query("SELECT NextQuestion FROM Answers WHERE QuestionNumber = $sqlALastQuestionAnswered AND PKID = $sqlBAnswer");
//If the operation produces an error, output an error message
if (!$sqlC) {
    die('Invalid query for SQLC: ' . mysql_error());
}
//Count the number of rows output
$sqlCCount = mysql_num_rows($sqlC);
//If rows exist, define the values
if ($sqlCCount > 0) {
    while ($row = mysql_fetch_array($sqlC)) {
        $sqlCNextQuestion = $row["NextQuestion"];
    }
}

最后我需要的是一个值,一个值仅用于sqlCNextQuestion,但我无法围绕键和值等等,无论我阅读了多少文档。如果有人能解释并告诉我如何实现我所追求的,我将不胜感激!

谢谢 :)

4

2 回答 2

3

目前在您的代码中, $sqlBAnswer 不是一个数组,而只是一个普通变量。你的代码:

if ($sqlBCount > 0) {
    while ($row = mysql_fetch_array($sqlB)) {
        $sqlBAnswer = $row["Answer"];
    }
}

只需遍历查询结果中的行,并在每一行中将 $row["Answer"] 的值重新分配给 $sqlBAnswer。

如果要将这些值保存到数组中,只需执行以下操作:

$sqlBAnswer = array(); //that creates a blank array to assign values to
if ($sqlBCount > 0) {
    while ($row = mysql_fetch_array($sqlB)) {
        $sqlBAnswer[] = $row["Answer"]; //note the '[]', which tells php to add the new value to the array
    }
}

然后,您可以通过以下方式进行 foreach:

foreach($sqlBAnswer as $value){
    // use your code with $sqlBAnswer substituted by $value
}

但是 - 至于你最终将如何选择你想要的 $sqlCAnswer 值,你没有充分描述你想要什么让我回答这个问题。此代码将遍历 $sqlBAnswer 的所有值,并可能产生许多 $sqlCAnswer 值(取决于您的数据库)-因此您需要改进您的问题或弄清楚自己如何解决该问题。

于 2013-01-29T09:33:09.303 回答
0

问题1的解决方案

$sqlBAnswer = $row["Answer"];

应该

$sqlBAnswer[] = $row["Answer"];

我知道你提到它只存储“数组”。但这不是真的,它正确地创建了数组,只是你在这里错误地访问它

$sqlC = mysql_query("SELECT NextQuestion FROM Answers WHERE QuestionNumber = $sqlALastQuestionAnswered AND PKID = $sqlBAnswer");  // No index being provided for array access

在你提到的 foreach 中,这将如下所示

foreach($sqlBAnswer as $ans)
{
$sqlC = mysql_query("SELECT NextQuestion FROM Answers WHERE QuestionNumber = $sqlALastQuestionAnswered AND PKID = $ans");
}
于 2013-01-29T09:30:50.570 回答