我创建了一个访问我的数据库的类。简化类如下(我将其命名为dbaccess.php)
class dbaccess {
function read($db) {
$con = mysqli_connect($db);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM equipment");
while($row = mysqli_fetch_array($result)){
$print = $print . $row['ID'] . " " . $row['name'] . " " . $row['new_price'] . " " . $row['residual_value'] . "<br>";
}
echo $print;
mysqli_close($con);
}
}
要访问该类,我使用此代码
include './dbaccess.php';
//define db address
$add = '"localhost","myuser","mypassword","mydbname"';
$db = new dbaccess;
$db->read($add);
此代码生成
Failed to connect to MySQL: Unknown MySQL server host '"localhost","myuser","mypassword","mydbname"'(2)
我不知道如何修复它,这里的任何人都可以帮助我吗?
答案 0 :(得分:4)
您将一个字符串传递给mysqli_connect
。您需要将"localhost"
,"myuser"
,...作为单独的变量传递。
答案 1 :(得分:0)
我和你的有类似的东西,从dropbox下载我的文件并查看内部 DB Connect
答案 2 :(得分:0)
class dbaccess {
function read($db) {
$con = mysqli_connect($server, $user, $password, $dbname);
(...)
然后在你的代码中,你应该划分参数。
include './dbaccess.php';
//define db address
$db = new dbaccess;
$db->read("localhost","myuser","mypassword","mydbname");
答案 3 :(得分:0)
将主机,用户名,密码和数据库存储在单独的变量中可能更好一点:
$host = "localhost";
$user = "myuser";
$pass = "mypassword";
$data = "mydbname";
$db = new dbaccess(); // <-- It's good practice to use parentheses in the constructor statement.
$db->read($host,$user,$pass,$data);
然后你的dbaccess
类的实现可能更像是这样:
$con = mysqli_connect($host,$user,$pass,$data);
这是因为mysqli_connect
函数将主机,用户名等视为单独的参数,而不是单个字符串。