gpt4 book ai didi

php - "Undefined Variable"通知

转载 作者:行者123 更新时间:2023-12-03 23:16:55 24 4
gpt4 key购买 nike

我是 php 新手,所以我相信这很简单。我收到这个错误

Notice: Undefined variable: conn in C:\Dev\Webserver\Apache2.2\htdocs\EclipsePHP\thecock\php\db.php on line 23

对于这段代码

<?php
$host = "localhost"; $database = "dbname"; $username = "user"; $password = "pass";

$conn = new mysqli($host, $username, $password, $database);

if (! $conn) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}else{
echo("all ok!");
}

function getContent($id) {
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) { # line 23
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
?>

如何修复通知?

最佳答案

将您的功能更改为:

function getContent($id, $conn) {
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) {
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}

您没有在函数范围内声明“原始”$conn。在函数内部,您只能访问在函数内部声明或通过参数提供的变量。

另一种方法是在函数中将变量声明为 global:

function getContent($id) {
global $conn;
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) {
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}

但是如果没有其他办法,你应该只这样做。全局变量使调试和维护代码变得困难。

另见 Variable scopewhy global variables are bad .

编辑:

是的你可以有一个数据库类:

class DB {
private static $conn = null;

public static function getConnection() {
if (is_null(DB::$conn)) {
$host = "localhost"; $database = "dbname"; $username = "user"; $password = "pass";
DB::$conn = new mysqli($host, $username, $password, $database);
}
return DB::$conn;
}
}

当然这不是最好的实现;)但它应该给你正确的想法。然后你可以获得连接:

DB::getConnection()

关于php - "Undefined Variable"通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2146046/

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