Haruna Ado Haruna Ado - 2 years ago 152
MySQL Question

Login Script in php to my MYSQL shows Deprecated warning

I'm writing a simple program in php that requires users to login. I have a working code but whenever a wrong username or password is entered, I got an exception that says the following:

Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\Directory\login.php on line 67

The script I have is working well, but I just need to get rid of this warning message.
Below is my php code.

$username = $_POST['username'];
$password = $_POST['password'];

// Connect to the database
$con = mysql_connect('localhost', 'root', '');

// Make sure we connected succesfully
if (!$con) {
die('Connection Failed' . mysql_error());
// Select the database to use
mysql_select_db("Garden", $con);

$q = mysql_query("select * from register where username='" . $username . "' and password='" . $password . "' ") or die(mysql_error());
$res = mysql_fetch_row($q);
if ($res) {
} else {
echo 'Error. The Username or Password that you entered is invalid.';

I dont know if im using something. This is my first time of using php. Please I need your help. Thank you.

Answer Source

Here's the same code using MySQLi:

$mysqli = new mysqli('localhost', 'user', 'password', 'db_name');
    printf("DB Connect failed: %s\n", mysqli_connect_error());
// Add the UTF8 Support
$mysqli->query("SET NAMES 'utf8'");
$mysqli->query("SET CHARACTER SET utf8");

$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$username = $mysqli->real_escape_string($username);
$password = $mysqli->real_escape_string($password);
$query = "SELECT * FROM `register` WHERE username='" . $username . "' and password='" . $password . "' LIMIT 1";
$result = $mysqli->query($query);
    if($result->num_rows == 1) {
        header("Location: home.php");
    } else {
        echo "Error. The Username or Password that you entered is invalid.";
$mysqli = null;

You shouldn't be avoiding the PHP Errors. You should always fix the code accordingly. You can use PDO or MySQLi.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download