3

我有一个有效的 SQL 语句,当我在 MAMP 上检查它时返回了正确的结果。

SELECT `questions`.`questionID` AS question, `questions`.`questionText`, 
       `questions`.`categoryID`,`answers`.`answerID`,`answers`.`answerText`,
       `answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`

但我不知道如何用 php 打印输出。请帮忙。这是代码:

<html>
<body>

<?php
    header('Content-Type: text/html; charset=utf-8');
    $con=mysqli_connect("localhost","root","root","Theory");
    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    $result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions`   .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`
                                 FROM `questions`,`answers`
                                 WHERE `questions`.`questionID` = `answers`.`questionID`");

    if (!$result)
    {
        die('Error: ' . mysqli_error($con));
    }
   while($row = mysqli_fetch_array($result))
   {
       echo "{";
       echo "{" . $row['questions'.'questionID'] . "}";   //this is not the full print
       echo "{" . $row['questions'.'questionText'] . "}"; //just for chaking
       echo "}";
   }

    mysqli_close($con);
    ?>

</body>
</head>

我得到:“{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{ }}”回应道。

4

2 回答 2

7

您在 if 条件中再次执行查询...但是$sql查询为空,因为未定义变量!

替换if (!mysqli_query($con,$sql))为, if (!$result)因为您已经在上面的行中执行了查询。

编辑以回答问题的评论:

当您获取结果数组时,您不需要指定表别名,只需指定列名或列别名(如果存在)。

试试这个:

while($row = mysqli_fetch_array($result))
{
   echo "{";
   echo "{" . $row['questionID'] . "}";   //this is not the full print
   echo "{" . $row['questionText'] . "}"; //just for checking
   echo "}";
}
于 2013-07-15T15:25:24.883 回答
5

$sql显然没有设置。你可以做:

$result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions`   .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`
                             FROM `questions`,`answers`
                             WHERE `questions`.`questionID` = `answers`.`questionID`");

if (!$result)
{
    die('Error: ' . mysqli_error($con));
}
于 2013-07-15T15:24:21.130 回答