I Need help with converting mysql_escape_string() into mysqli_real_escape_string()

General discussions related to php

Moderators: egami, macek, gesf

Post Reply
visitor52
New php-forum User
New php-forum User
Posts: 2
Joined: Sun Nov 05, 2017 4:27 pm

Sun Nov 05, 2017 4:55 pm

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:

Code: Select all

<?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:

Code: Select all

<?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)

Code: Select all

<?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())

Code: Select all

<?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()?

Code: Select all

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

User avatar
benanamen
New php-forum User
New php-forum User
Posts: 42
Joined: Mon Oct 16, 2017 1:06 pm

Sun Nov 05, 2017 6:18 pm

Please refer to my replies in the other three forums you posted this.
The XY Problem
The XY problem is asking about your attempted solution (X) rather than your actual problem (Y). This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.

visitor52
New php-forum User
New php-forum User
Posts: 2
Joined: Sun Nov 05, 2017 4:27 pm

Tue Nov 07, 2017 6:35 am

Refer to what? To your flooding my threads with your negative, unsubstantiated, unhelpful statements? You do not offer any help, any solution, not a single line of code. You admitted that you do not deal with MySQL and do not know MySQLi. Then why you bother to post in this thread which is related to MySQL?! All you do is sabotaging my threads; thus, breaking the rules. If you can't help, please do me a favor, do not post in my thread.

User avatar
benanamen
New php-forum User
New php-forum User
Posts: 42
Joined: Mon Oct 16, 2017 1:06 pm

Tue Nov 07, 2017 10:12 am

OP, if you do not stop trolling all the various forums I am going to start reporting you.

Get it through your head, nobody is going to write your code for free. You come off totally lame saying no one has given you any code when you yourself have said you are not a programmer and don't know php.

What you are really saying is not give me code, but "Somebody write my code for me for free". Everyone on every forum you are trolling on is quite aware you just want free code and not willing to make any attempt whatsoever to learn anything on your own.

You already have one thread that has been shutdown. Don't be surprised when the rest of them are.
The XY Problem
The XY problem is asking about your attempted solution (X) rather than your actual problem (Y). This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.

thinsoldier
New php-forum User
New php-forum User
Posts: 24
Joined: Sat Dec 02, 2017 3:12 pm

Sat Dec 02, 2017 3:47 pm

I am sympathetic to your plight "visitor52", but benanamen is correct.

If I was really really bored and you had posted at least some code changes that you had tried on your own I might have held your hand as you fixed it yourself. If you are not going to try to write any code yourself, nobody will help you. You need to pay someone to fix it.

If the original code was written in 2004 you should have paid someone by at least 2014 to check it for security vulnerabilities and update it to be future proof.

I'll throw you a bone: If the code actually still works and you're just upset about some ugly deprecation warning messages there's an easy way to make those messages disappear... at least until the day when your hosting provider upgrades your server to PHP 7, which could be years if you're lucky.

But that advice is based on a wild guess because you didn't provide enough specific information to go on.

Post Reply