我正在为一个学校项目制作一个添加到篮子的脚本,但这会导致我一些错误。
我有一个add.php和index.php文件,他们一起工作。
add.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");
?>
我在index.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 第624行的C:\ xampp \ htdocs \ index.php
警告:mysqli_fetch_assoc()期望参数1为mysqli_result, 在第626行的C:\ xampp \ htdocs \ index.php中给出的null
有人可以尝试向我解释一下,因为我还有点新的PHP吗?
答案 0 :(得分:0)
您的连接变量是
$DBConnect = new mysqli("localhost","root","","test");
SO使用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);
}