PHP5 to PHP7 DatabaseConnection

I am look at an old PHP project that uses mysql_connect, and I am trying to update it to PHP 7, by using mysqli_connect.

In the original project, I had a file - connect.php which had the database info, I would then include that file where needed.  But I cant seem to get this to work in PHP7

Original file looked like this.

 <?php
// Connects to my Database
mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
?>

I have changed to this

<?php

$con=mysqli_connect("your.hostaddress.com", "username", "password","Database_Name");

?>

now on  a page where I had

return mysql_real_escape_string($data);

and am now trying to use

return mysqli_real_escape_string($con, $data);

and I get the error con is not defined.

How can i keep the original structure but update to PHP7
dkilbyAsked:
Who is Participating?
 
Chris StanyonConnect With a Mentor Commented:
Add some error checking to your connection page. Turn on error reporting at the start of it, and then explicitly check the connection:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$con = mysqli_connect("your.hostaddress.com", "username", "password", "Database_Name");

if (! $con) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

Open in new window

In the page where you need to use it, try a require_once("connection.php") instead of an include and see what you get. If it fails, you should at least get some useful debugging info.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.