Mysql is deprecated. I have a code in mysql that I would like to convert to mysqli, but I don't succeed.
The code works, but I have error messages "The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead"
Here is the initial code:
$connection = mysql_connect('host','root','password') or die ("Couldn't connect to server.");
$db = mysql_select_db('database_name', $connection) or die ("Couldn't select database.");
$result = mysql_query("SELECT * FROM customers WHERE cust_number ='$Cust_Number' ");
if( mysql_num_rows($result) > 0) {
mysql_query("UPDATE `customers` SET cust_name='$Cust_Name', cust_phone='$Cust_Phone', cust_phone1='$Cust_Phone1', cust_email='$Cust_Email', cust_address='$Cust_Address' ");
}
else
{
mysql_query("INSERT INTO customers (cust_number, cust_name, cust_phone, cust_phone1, cust_email, cust_address) VALUES ('$Cust_Number', '$Cust_Name', '$Cust_Phone', '$Cust_Phone1', '$Cust_Email', '$Cust_Address') ");
}
I tried the following conversion:
$connection = mysqli_connect('host','root','password') or die ("Couldn't connect to server.");
$db = mysqli_select_db($connection,'database_name') or die ("Couldn't select database.");
if( mysqli_num_rows($result) > 0) {
mysqli_query($connections,"UPDATE `customers` SET cust_name='$Cust_Name', cust_phone='$Cust_Phone', cust_phone1='$Cust_Phone1', cust_email='$Cust_Email', cust_address='$Cust_Address' ");
}
else
{
mysqli_query($connections,"INSERT INTO customers (cust_number, cust_name, cust_phone, cust_phone1, cust_email, cust_address) VALUES ('$Cust_Number', '$Cust_Name', '$Cust_Phone', '$Cust_Phone1', '$Cust_Email', '$Cust_Address') ");
}
But it doesn't work.
Can someone help me convert the initial code in mysqli or PDO?
Your mysqli_query()
calls $connections
, whereas your connection is $connection
-- this is why your code is failing.
It is, however, worth noting that as it stands, your code is vulnerable to SQL injection. To avoid this, you'll want to make use of prepared statements (something which didn't exist with the MySQL connector).
This can be done with the following:
$connection = mysqli_connect('host','root','password') or die ("Couldn't connect to server.");
$db = mysqli_select_db($connection,'database_name') or die ("Couldn't select database.");
if (mysqli_num_rows($result) > 0) {
$stmt = $this->mysqli->prepare("UPDATE `customers` SET cust_name='?', cust_phone='?', cust_phone1='?', cust_email='?', cust_address='?'");
$stmt->bind_param('sssss', $Cust_Name, $Cust_Phone, $Cust_Phone1, $Cust_Email, $Cust_Address);
$stmt->execute();
}
else
{
$stmt = $this->mysqli->prepare("INSERT INTO customers (cust_number, cust_name, cust_phone, cust_phone1, cust_email, cust_address) VALUES ('?', '?', '?', '?', '?', '?') ");
$stmt->bind_param('ssssss', $Cust_Number, $Cust_Name, $Cust_Phone, $Cust_Phone1, $Cust_Email, $Cust_Address);
$stmt->execute();
}