Change real_escape_string to mysqli_real_escape_string for Function safeEscapeString in PHP 7.0

This entry is part 1 of 2 in the series PHP Programming

I often use function safeEscapeString from  in my PHP projects. It helps sustain the integrity of data coming to and from MySQL or similar database. However, if the code ran on PHP 5.4 or 5.6 at the highest, and I wanted it to run PHP 7.0, the latest and greatest version of PHP. When the error reporting is turned on, a fatal error in code will appear. The solution is to use the recommended function mysqli_real_escape_string, which takes two parameters, the link and the string to sanitize.

$temp2 = mysqli_real_escape_string($link, $temp2);

Since I had not had a special link to a database, I just added one to get the $link variable (as shown here):

$link = mysqli_connect("localhost", "my_user", "my_password", "my_db");

The complete function looks like this:

Function safeEscapeString($string)
{
$temp1 = str_replace("[br]", "", $temp2);
$temp2 = str_replace("[br /]", "", $temp1);

if (get_magic_quotes_gpc())
{
return $temp2;
}
else
{
$link = mysqli_connect("localhost", "my_user", "my_password", "my_db"); 
if (!$link) { 
if($local_print){ 
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; } 
} else { 
if($local_print){ 
echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL; 
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL; 
} 
} 
$temp2 = mysqli_real_escape_string($link, $temp2); 
mysqli_close($link); return $temp2; 
} 
}
 /////////////////////////////
Series NavigationUse pre Tag to Format Your PHP Code in WordPress Posts
This entry was posted in PHP, Programming and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.