Update depreciated mysql_connect()

1k views Asked by At

I have the following php code connecting my database with mysql_connect(), but I keep getting the following warning:

Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in .....

What would the correct way for me to update this connection so I don't have any problems in the future?

<?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");
?>

Edit : highlight the error to visible at a glance.

1

There are 1 answers

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

for more info see here http://php.net/manual/de/pdo.prepare.php