连接MySQL的几种方式

时间:2020-05-05

使用PDO连接

如果连接MySQL报错:SQLSTATE[HY000] [1045] Access denied for user 'root'@'192.168.1.4' (using password: YES)

请确认MySQL密码是否正确!

$dsn = 'mysql:dbname=test;host=192.168.1.100;port=3306;charset=utf8mb4';

$user = 'root';
$password = 'a@123456Dj';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
    exit();
}

$sql = 'SELECT * FROM student';

foreach ($dbh->query($sql) as $row) {
    print $row['name'] . "\t";
    print $row['age'] . "\t";
    print $row['status'] . "\n";
}

使用mysqli

$mysqli = new mysqli("192.168.1.100", "root", "a@123456Dj", "test");

if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$sql = 'SELECT * FROM student';

if ($result = $mysqli->query($sql)) {
    printf("Select returned %d rows.\n", $result->num_rows);

    while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
        var_dump($row);
    }

    $result->close();
}