1

我创建了一个类来访问我的数据库。简化的类如下(我将其命名为 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)

我不知道如何解决它,这里有人可以帮助我吗?

4

4 回答 4

4

您将单个字符串传递给mysqli_connect. 您需要将"localhost", "myuser",... 作为单独的变量传递。

http://php.net/manual/en/function.mysqli-connect.php

于 2013-08-05T16:02:29.507 回答
0

我有类似的东西,从保管箱下载我的文件并查看 DB Connect

于 2013-08-05T16:03:03.913 回答
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");

REF

于 2013-08-05T16:03:35.490 回答
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函数将主机、用户名等作为单独的参数,而不是作为单个字符串。

于 2013-08-05T16:06:52.447 回答