更新已弃用的mysql_connect()

时间:2016-12-29 21:26:50

标签: php mysql database deprecated mysql-connect

我有以下PHP代码用 mysql_connect()连接我的数据库,但我一直收到以下警告:

  

不推荐使用:mysql_connect():不推荐使用mysql扩展   将来将被删除:使用mysqli或PDO代替......

我更新此连接的正确方法是什么,以便将来我没有任何问题?

<?php
//CREATED BY ...
/*
1: "die()" will exit the script and show an error statement if something goes wrong
2: A "mysql_connect()" error usually means your username/password are wrong
3. A "mysql_select_db()" error usually means the database does not exist
*/
//Place db host name. Sometimes "localhost" but
//sometimes looks like this: >> ???mysql??.someserver.net
$db_host = "localhost";
//Place the username for the MySQL database here
$db_username = "...";
//Place the password here:
$db_pass = "...";
//Place the name for the MyS
$db_name = "...";

//Run the connection right here!
mysqli_connect("$db_host","$db_username","$db_pass") or die ("could not connect");
mysql_select_db("$db_name") or die("no databases");
?>

编辑:突出显示错误,一目了然。

1 个答案:

答案 0 :(得分:0)

try {
    $dbh = new PDO("mysql:dbname=$db_name;host=$db_host", $db_username, $db_pass);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

了解更多信息,请参阅此处http://php.net/manual/de/pdo.prepare.php