我在标题为sample.php
的PHP文件中跟踪了一个函数的代码:
function deleteValue($value) {
$servername = "localhost";
$username = "root";
$password = "jumbo";
$dbname = "demo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "DELETE FROM user WHERE value = '$value'";
if ($conn->query($sql) === TRUE) {
$conn->close();
return true;
} else {
$conn->close();
return false;
}
}
实际上,在这个文件(sample.php
)中有太多这样的函数会重复以下数据库连接代码:
$servername = "localhost";
$username = "root";
$password = "jumbo";
$dbname = "demo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
然后,我在同一文件夹中创建了一个标题为db.php
的文件,并将上述代码添加到其中。在文件开头使用require_once('db.php');
sample.php
'我将文件包含在上面的代码中。最后代码如下:
require_once('db.php');
function deleteValue($value) {
$sql = "DELETE FROM user WHERE value = '$value'";
if ($conn->query($sql) === TRUE) {
$conn->close();
return true;
} else {
$conn->close();
return false;
}
}
现在它给了我500内部服务器错误。
甚至不是通过在文件db.php
的开头粘贴sample.php
的整个代码来尝试包含我尝试过的文件,但仍然会出现500内部服务器错误。
$servername = "localhost";
$username = "root";
$password = "jumbo";
$dbname = "demo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function deleteValue($value) {
$sql = "DELETE FROM user WHERE value = '$value'";
if ($conn->query($sql) === TRUE) {
$conn->close();
return true;
} else {
$conn->close();
return false;
}
}
有人可以纠正我在我的代码中犯的错误吗?
提前致谢。
答案 0 :(得分:0)
我建议你在 db_config.php 文件中,你应该只使用数据库配置和这样的函数:
$servername = "localhost";
$username = "root";
$password = "jumbo";
$dbname = "jumbo_jet";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
在 common.php 中使用这样的代码:
require_once("db_config.php");
function deleteToken($receivedToken) {
global $conn;
$sql = "DELETE FROM user_login WHERE token = '$receivedToken'";
if ($conn->query($sql) === TRUE) {
return true;
}
return false;
}
我希望它对你有用。如果有的话,请告诉我。