• PHP Help PHP Coding
  • I Need help with converting mysql_escape_string() into mysqli_real_escape_string()

Hello all! I'm not a programmer and don't know PHP - this is the only reason I'm asking you for help. Back in 2004, I acquired a script for generating dynamic php pages for users' reviews - this the only small section of my website where PHP is employed. Since then, the standard command MySQL and functions related to it, particularly mysql_escape_string(), have been deprecated, and now I must replace them with MySQLi command and its functions. I understand that solving this issue is a simple task for most of you, but it is a "mission impossible" for me having no special education and knowledge. Could you please modify the attached code snippets? Thank you for your understanding and time!

Below are a few fragments that require modification. If something is missing and required for complete piece of code, please let me know. Also, do I have to create a special file for connecting to a database, or could I use the existing 'functions.php' file (also shown below)?

1) To get access to Admin Area:

<?php
//if a session does not yet exist for this user, start one
session_start();

//if there is no username or password entered and the user has not already been validated, send user back to login page.
if ((empty($_POST["admin_username"]) || empty($_POST["admin_passtext"])) && empty($_SESSION['valid_user']))
			{
			Header("Location: index.php");
			}

include ("../body_edit.php");
include ("../config.php");
include ("../functions.php");

//make sure user has been logged in.
if (empty($_SESSION['valid_user']))
	{
	// User not logged in, check database
//Check to see that the username and Password entered have admin access.
$sqlaccess = "SELECT username, passtext
		FROM admin 
		WHERE username='" . mysql_escape_string($_POST['admin_username']) . "' 
		AND passtext = '" . mysql_escape_string($_POST['admin_passtext']) . "'
		LIMIT 1
		";

$resultaccess = mysql_query($sqlaccess)
or die(sprintf("Couldn't execute sql_count, %s: %s", db_errno(), db_error()));

$numaccess = mysql_numrows($resultaccess);

if ($numaccess == 0) {
BodyHeader("Access Not Allowed!");
?>
<style type="text/css">
<!--
.style1 {color: #FF0000}
.style2 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 12px;
}
.style3 {font-family: Arial, Helvetica, sans-serif; font-size: 14px; }
-->
</style>
<P>To access the Administration area you need to have approved access. The username and Password (<?php echo "$admin_username and $admin_passtext"; ?>) you entered are not approved!<br>
  <a href="index.php">Please try again</a>
  <?php
BodyFooter();  
exit; }// if numaccess //if the user/pass were valid create a session for the user. $_SESSION['admin_passtext'] = $_POST['admin_passtext']; $_SESSION['admin_username'] = $_POST['admin_username']; //since user has been verified, set a session for checking on admin pages. $_SESSION['valid_user'] = $_POST['admin_username']; //set cookie so admin can save login info if logout link is not clicked. if (empty($_COOKIE['admin_username']) && empty($_COOKIE['admin_passtext'])) { setcookie("admin_username", $_POST['admin_username'], time() + 31536000, "/"); setcookie("admin_passtext", $_POST['admin_passtext'], time() + 31536000, "/"); }//if cookie }//if session BodyHeader("$sitename Administration Menu"); //Get the number of reviews that are not approved. $result = mysql_query("SELECT COUNT(*) as total FROM review WHERE approve='n' AND review_item_id != '0'") or die(sprintf("Couldn't execute sql_count, %s: %s", db_errno(), db_error())); $rows = mysql_fetch_array($result); $total = $rows["total"]; //Get the total number of reviews that are approved. $result = mysql_query("SELECT COUNT(*) as totaly FROM review WHERE approve='y'") or die(sprintf("Couldn't execute sql_count, %s: %s", db_errno(), db_error())); $rows = mysql_fetch_array($result); $totaly = $rows["totaly"]; //Get the total number of user submitted items that need to be approved. $result = mysql_query("SELECT COUNT(*) as totalitemuser FROM review_items_user") or die(sprintf("Couldn't execute sql_count, %s: %s", db_errno(), db_error())); $rows = mysql_fetch_array($result); $totalitemuser = $rows["totalitemuser"]; ?> //some code here.... <?php BodyFooter(); exit; ?>

2) In my file functions.php:

<?php

$NumReviews = 8;

$db_name = "xxxxxxxxxxxxxxxxx";

$connection = @mysql_connect("xxxxxxxxx", "xxxxxxxxxxxx", "xxxxxxxxxxxx")

or die("Couldn't connect.");

$db = @mysql_select_db($db_name, $connection)

or die("Couldn't select database.");

function db_errno($args=array()) {

return @mysql_errno();

}
function db_error($args=array()) {

return @mysql_error();

}
?>

Other code snippets with MySQL functions:

3)

<?php
session_start();

include ("body_form.php");
include ("functions.php");
include ("config.php");

//some code here........

$sql = "SELECT * FROM 
			review_items
			WHERE 
			item_id = $item_id";

		$sql_result = mysql_query($sql)
	or die(sprintf("Couldn't execute query, %s: %s", db_errno(), db_error()));

while ($row = mysql_fetch_array($sql_result)) { 
$item_name = stripslashes($row["item_name"]); 
$item_desc = stripslashes($row["item_desc"]); 
$item_type = stripslashes($row["item_type"]); 
}
BodyHeader("Submit review for $item_name");
?>

4) (in this snippet, there is also another deprecated function - preg_replace())

<?php
session_start();

include ("body_form.php");
include ("functions.php");
include ("config.php");

//some code here........

//check user input and remove any reference to javascript.
$errjava = "<font color=red><BR><BR><B>No Javascript is allowed!  Please click edit and remove the offending code.<BR><BR></B></font>";

$summary = preg_replace("'<script[^>]*?>.*?</script>'si", "$errjava", $summary);
$review = preg_replace("'<script[^>]*?>.*?</script>'si", "$errjava", $review);
$source = preg_replace("'<script[^>]*?>.*?</script>'si", "$errjava", $source);
$location = preg_replace("'<script[^>]*?>.*?</script>'si", "$errjava", $location);

//replace bad words
$sql_filter = "select badword, goodword
from review_badwords
";

$sql_result_filter = mysql_query($sql_filter)
		or die(sprintf("Couldn't execute query, %s: %s", db_errno(), db_error()));

while ($filter = mysql_fetch_array($sql_result_filter)) {
			$review = preg_replace('/'.$filter['badword'].'/i', $filter['goodword'], $review);
			$summary = preg_replace('/'.$filter['badword'].'/i', $filter['goodword'], $summary);
			$source = preg_replace('/'.$filter['badword'].'/i', $filter['goodword'], $source);
			$location = preg_replace('/'.$filter['badword'].'/i', $filter['goodword'], $location);
}

$review = nl2br($review);


//set_magic_quotes_runtime(0);
BodyHeader("Confirm $item_name Review");
?>

5) Can mysql_format() be simply replaced with mysqli_format()?

$review = mysql_format($review);
$summary=  mysql_format($summary);
$source = mysql_format($source);
$location = mysql_format($location);

    As I mentioned in your other forum you cross posted on, your script requires a complete re-write. This is not a conversion. It is not likely someone is going to write a script for free. I would recommend you hire someone if you need this done.

      benanamen;11064599 wrote:

      As I mentioned in your other forum you cross posted on, your script requires a complete re-write. This is not a conversion. It is not likely someone is going to write a script for free. I would recommend you hire someone if you need this done.

      I would do that if I wasn't unemployed and had money. I'm not asking for a new script. This script must be re-written because of usage of MySQLi? Will it not work if I just make appropriate MySQLi connection to database and replace all MySQL functions with MySQLi ones?

        While there are multiple issues with the code, partly due to age and lack of maintenance, and partly because of some suspect coding at the outset, the immediate question of replacing mysql functions with mysqli functions is generally just one of (a) renaming the functions (which typically reduces to adding the 'i' but each page of the manual for one of the deprecated functions (e.g., [man]mysql_query[/man]) includes a link to its replacement, and (b) providing the [font=monospace]$connection[/font] value to each one (because the functions no longer just guess which database connection you want to use).

          4) (in this snippet, there is also another deprecated function - preg_replace())

          No. There's nothing wrong with preg_replace or it's usage in the posted code. AFAIK only the /e modifier has been deprecated, which the code is not using.

          5) Can mysql_format() be simply replaced with mysqli_format()?

          No. This function is not a php function, but a user written function somewhere in the code you have. The function name and its call can remain as is, assuming that the code inside the function doesn't use any mysql_ statements.

          You will also want to remove all the @ error suppressors in the code, since they hide problems, both when the code normally runs (you should log all php errors when on a live server) and during any conversion of the code.

            Weedpacket;11064603 wrote:

            While there are multiple issues with the code, partly due to age and lack of maintenance, and partly because of some suspect coding at the outset, the immediate question of replacing mysql functions with mysqli functions is generally just one of (a) renaming the functions (which typically reduces to adding the 'i' but each page of the manual for one of the deprecated functions (e.g., [man]mysql_query[/man]) includes a link to its replacement, and (b) providing the [font=monospace]$connection[/font] value to each one (because the functions no longer just guess which database connection you want to use).

            Weedpacket, thank you very much for your response! Yes, I will replace MySQL functions with their MySQLi replacements listed in the manual. But what code do I need for establishing $connection value to each one? This is where I'm completely lost as I can't program in PHP.
            "some suspect coding at the outset" - could you explain this? So far, the script has been working even with deprecated MySQL functions, so is the suspect coding a critical factor?

              pbismad;11064605 wrote:

              No. There's nothing wrong with preg_replace or it's usage in the posted code. AFAIK only the /e modifier has been deprecated, which the code is not using.

              pbismad, thank you very much for your input!

              Sorry, I couldn't find the /e modifier in my code snippets. Is it this symbol: '/i'?
              I decided to remove the "bad words" filter. With the user's input, I created this code with the preg_replace function (will it work ok?):

              $summary = preg_replace("/[^A-Za-z0-9- !?.,]/","", $summary);
              $review = preg_replace("/[^A-Za-z0-9- !?.,]/","", $review);
              $source = preg_replace("/[^A-Za-z0-9- !?.,]/","", $source);
              $location = preg_replace("/[^A-Za-z0-9- !?.,]/","", $location);
              
              pbismad;11064605 wrote:

              No. This function is not a php function, but a user written function somewhere in the code you have. The function name and its call can remain as is, assuming that the code inside the function doesn't use any mysql_ statements.

              Sorry about this question. I overlooked this "user written function".

              pbismad;11064605 wrote:

              You will also want to remove all the @ error suppressors in the code, since they hide problems, both when the code normally runs (you should log all php errors when on a live server) and during any conversion of the code.

              Ok, great! I'll sure remove all @'s!

              Thanks a lot!

                pbismad;11064605 wrote:

                ...the /e modifier has been deprecated, which the code is not using.

                pbismad, I see now that you mentioned it. Sorry. My bad.

                Could you please explain the '/i' symbol? I couldn't find any info on this on the web.

                  4 days later
                  visitor52;11064697 wrote:

                  dalecosp, thank you for explaining! And that php cheat sheet is helpful!

                  You're quite welcome. 🙂

                    8 days later

                    It took me a few days to modify my old script and fix all errors shown in the PHP code checker, but now the script is working just fine! And I didn't have to re-write it completely as one person strongly suggested. All I had to do was really just to establish a MySQLi link to a database and then replace all MySQL functions with their MySQLi equivalents according to the PHP Manual. With help from good people in other forums, I could do it, and it was not an impossible task even for a noob like myself! The problem was solved!

                      Write a Reply...