加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 使用INNER JOIN打印mySQL查询的结果

发布时间:2020-12-13 22:05:37 所属栏目:PHP教程 来源:网络整理
导读:我有一个工作的SQL语句,当我在MAMP上检查它时返回了正确的结果. SELECT `questions`.`questionID` AS question,`questions`.`questionText`,`questions`.`categoryID`,`answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`FROM `questions`,`ans
我有一个工作的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","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`   .`categoryID`,`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>

我得到:“{{} {}} {{} {}} {{} {}} {{} {}} {{} {}} {{} {}} {{} {}} {{} { “回声.

解决方法

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

因为你已经在上面的行中执行了查询,所以用if(!$result)替换if(!mysqli_query($con,$sql)).

编辑回答问题的评论:

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

试试这个:

while($row = mysqli_fetch_array($result))
{
   echo "{";
   echo "{" . $row['questionID'] . "}";   //this is not the full print
   echo "{" . $row['questionText'] . "}"; //just for checking
   echo "}";
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读