早上好, 我对此问题进行了广泛的研究,但是不幸的是,没有任何相关问题解决了我的问题。
这里,我有一个非常基本的PHP mySQLi db连接。连接成功,在表上运行的查询也将成功。问题是结果集将不会显示。我所有的引用都是正确的,当我检查是否填充了结果集时,它就是正确的。我相信问题出在我的while块上,但是运行时不会返回任何错误。 谢谢您的时间
<?php
$db = mysqli_connect('localhost','root','','securitour') //connection to the database
or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<?php
$query = "SELECT * FROM location"; //The SQL query
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query); //query the table an store the result set in a variable
$row = mysqli_fetch_array($result); //create an array and store the records of the result set in it
if (mysqli_num_rows($result) != 0) //to check if the result set contains data
{
echo "results found"; //THIS is what is returned.
}
else
{
echo "results not found";
}
while ($row = $result->fetch_assoc()) //itterate through the array and display the name column of each record
{
echo $row['name'];
}
mysqli_close($db);
?>
</body>
</html>
答案 0 :(得分:1)
您无需运行mysqli_query()
两次。并且您需要将mysqli_fetch_assoc
用于关联数组
<?php
$db = mysqli_connect('localhost','root','','securitour') or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<?php
$query = "SELECT * FROM location"; //The SQL query
$result = mysqli_query($db, $query) or die('Error querying database.'); //query the table an store the result set in a variable
$row = mysqli_fetch_assoc($result); //create an array and store the records of the result set in it
if (mysqli_num_rows($result) != 0) //to check if the result set contains data
{
echo "results found"; //THIS is what is returned.
} else {
echo "results not found";
}
foreach ( $row as $name=>$val) {
echo $name . ':' . $val . '<br>';
}
mysqli_close($db);
?>
</body>
</html>
答案 1 :(得分:1)
很多东西不在这里。
您正在处理mysqli_query()函数两次-不需要。
您正在选择SQL查询(SELECT *)中的所有字段。您应该按名称选择字段。
尝试以下方法:
<?php
$db = mysqli_connect('localhost','root','','securitour') //connection to the database
or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<?php
$query = "SELECT name FROM location"; //The SQL query
$result = mysqli_query($db, $query) or die('Error querying database'); //query the table an store the result set in a variable
if(mysqli_num_rows($result) > 0){
echo "Results found!";
while($row = mysqli_fetch_array($result)){ //create an array and store the records of the result set in it
echo $row['name'];
}
} else {
echo "results not found";
}
mysqli_close($db);
?>
</body>
</html>