我正在为一个学校项目编写添加到篮子脚本,但它给我带来了一些错误。
我有一个 add.php 和 index.php 文件,他们一起工作。
添加.php如下所示:
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
if (empty($_SESSION['kurv'])) {
$_SESSION['kurv'] = array();
}
array_push($_SESSION['kurv'], $_GET['id']);
header("location: index.php");
?>
我在索引中的脚本.php显示放入数组中的元素如下所示:
<?php
$_SESSION['kurv'] = array();
$DBConnect = new mysqli("localhost","root","","test");
$arrayID = implode(',', $_SESSION['kurv']);
$sql = "SELECT * FROM produkter WHERE id IN ($arrayID)";
$result = $conn->query($sql);
while($row = mysqli_fetch_assoc($result)) { ?>
<table>
<tr>
<td><?php echo $row2['titel'];?></td>
<td class="h"><?php echo $row2['pris'] . " kr.";?> <button class="knap"><a>-</a></button></td>
</tr>
</table>
<?php
}
?>
但是由于某种原因,我无法解释并试图修复,这会导致我这些错误:
警告:mysqli::query():无法获取 mysqli C:''xampp''htdocs''index.php 在第 624 行
警告:mysqli_fetch_assoc() 预期参数 1 mysqli_result, null 在 C:''xampp''htdocs''index.php 第 626 行给出
有人可以尝试向我解释一下,因为我对 PHP 还有点陌生?
您的连接变量是
$DBConnect = new mysqli("localhost","root","","test");
所以使用DBConnect
$result = $DBConnect->query($sql);
而不是$conn
$result = $conn->query($sql);
使用num_rows检查查询是否返回结果
$sql = "SELECT * FROM produkter WHERE id IN ($arrayID)";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<table>
<tr>
<td><?php echo $row2['titel']; ?></td>
<td class="h"><?php echo $row2['pris'] . " kr."; ?> <button class="knap"><a>-</a></button></td>
</tr>
</table>
<?php
}
} else {
echo "NO result foumd";
}
检查查询和连接使用中的错误
/* check connection */
if ($DBConnect->connect_errno) {
printf("Connect failed: %s'n", $DBConnect->connect_error);
exit();
}
if (!$DBConnect->query("SET a=1")) {
printf("Errormessage: %s'n", $DBConnect->error);
}
阅读 http://php.net/manual/en/mysqli.error.php