gpt4 book ai didi

php - 当尝试在页面的两个部分中使用 PHP 时,为什么会出现 undefined variable 错误?

转载 作者:行者123 更新时间:2023-11-29 07:46:48 24 4
gpt4 key购买 nike

我尝试在页面的两个不同部分使用 PHP。但是当我尝试加载页面时,我收到错误: undefined variable $conn。为什么我会收到此错误?

<tbody>
<?php
$sql = "SELECT id, name, price FROM periperichicken";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>£" . $row["price"] . "</td>";
echo "<td><input type=\"text\" name=\"amount\"
class=\"amount-type\"
placeholder=\"Amount\"/></td>";
echo "<td><a href=\"\" class=\"add-cart\">Add to cart</a></td>";
echo "</tr>";
}
}
mysqli_close($conn);
?>
</tbody>

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pizza";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>

最佳答案

您在脚本顶部使用 $conn

$result = mysqli_query($conn, $sql);

但是你进一步定义它

$conn = mysqli_connect($servername, $username, $password, $dbname);

您需要将该部分移至第一个部分,然后才能运行任何查询。

<?PHP
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pizza";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>

<tbody>
<?php
$sql = "SELECT id, name, price FROM periperichicken";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>£" . $row["price"] . "</td>";
echo "<td><input type=\"text\" name=\"amount\" class=\"amount-type\" placeholder=\"Amount\"/></td>";
echo "<td><a href=\"\" class=\"add-cart\">Add to cart</a></td>";
echo "</tr>";
}
}

mysqli_close($conn);
?>
</tbody>

关于php - 当尝试在页面的两个部分中使用 PHP 时,为什么会出现 undefined variable 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27533605/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com