我试图用PDO替换旧的PHP代码,但我面临着两个主要问题。
首先,让我向您展示我的config
脚本,我在其中连接数据库:
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
?>
我的文件夹树:
www/
├── A/
├── main/
│ ├── test2.php
├── sys/
├── class/
│ ├── test.php
├── config.php
现在,第一个问题是PDO只有在我将config.php的require
放在一个函数中时才有效,就像在这个文件中一样, test.php :
<?php
function test(){
require_once('../config.php');
try {
$sql = "SELECT count(*) FROM chats";
$stmt = $conn->prepare($sql);
$stmt->execute();
return $number_of_rows = $stmt->fetchColumn();
}
$conn = null;
}
?>
//html is used only to show me if it works, it will be deleted from the final script
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<?php print_r(test()); ?>
</body>
</html>
我认为这是一个问题,因为这个文件会有数百个函数,我会在每个函数中写一个require_once
太脏,或者这是唯一的方法吗?
现在,第二个问题是即使 test.php 有效,当我尝试从 test2.php 中调用其中的函数时,它位于另一个文件夹,它不再向我显示任何内容。这是 test2.php 中的代码:
<?php
include('../sys/class/test.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<?php print_r(test()); ?>
</body>
</html>
关于如何解决这两个问题的任何想法? 无论如何,非常感谢你:))