我有一个有效的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>
我得到:“{{} {}} {{} {}} {{} {}} {{} {}} {{} {}} {{} {}} {{} {}} { {} {}}“回应。
答案 0 :(得分: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 "}";
}
答案 1 :(得分: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));
}