/    Sign up×
Community /Pin to ProfileBookmark

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:

[code=php]<?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;
?>[/code]

2) In my file functions.php:

[code=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();

}
?>[/code]

Other code snippets with MySQL functions:

3)

[code=php]<?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”);
?>[/code]

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

[code=php]<?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”);
?>[/code]

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

[code=php]$review = mysql_format($review);
$summary= mysql_format($summary);
$source = mysql_format($source);
$location = mysql_format($location);[/code]

to post a comment
PHP

28 Comments(s)

Copy linkTweet thisAlerts:
@benanamenNov 06.2017 — As I mentioned in the now four other forums, this requires a complete rewrite. Not likely someone will do it for free.
Copy linkTweet thisAlerts:
@phpmillionNov 06.2017 — Use this tool, it will convert whole script into mysqli in seconds - https://github.com/philip/MySQLConverterTool

Used it in the past, it did a great job even for complex scripts (containing hundreds if not thousands of PHP files). Some pages displayed minor warnings after conversion (scripts worked, however), but I was able to fix all of them in minutes.
Copy linkTweet thisAlerts:
@visitor52authorNov 06.2017 — Use this tool, it will convert whole script into mysqli in seconds - https://github.com/philip/MySQLConverterTool

Used it in the past, it did a great job even for complex scripts (containing hundreds if not thousands of PHP files). Some pages displayed minor warnings after conversion (scripts worked, however), but I was able to fix all of them in minutes.[/QUOTE]


phpmillion, thank you so much for your advise - I do appreciate it! I'm glad that there are kind people like you in the community, who are willing to provide helpful advises to unskilled persons like myself being in desperate situations.
Copy linkTweet thisAlerts:
@rootNov 06.2017 — Swap out the mysql_ for the mysqli_ and then work the errors.

The alternative is to write a polyfiller function to replace the mysql_ function with the results of running an mysli_ function...
Copy linkTweet thisAlerts:
@visitor52authorNov 06.2017 — Swap out the mysql_ for the mysqli_ and then work the errors.

The alternative is to write a polyfiller function to replace the mysql_ function with the results of running an mysli_ function...[/QUOTE]


Besides swapping out the mysql_ for the mysqli_ I need to establish a mysqli connection to the database. Could you please provide some code?

As for the polyfiller function, I have no idea how to write it. As I mentioned above, I'm not a programmer. ?
Copy linkTweet thisAlerts:
@visitor52authorNov 06.2017 — Use this tool, it will convert whole script into mysqli in seconds - https://github.com/philip/MySQLConverterTool[/QUOTE]

Dear phpmillion, can you tell me if the converter that you suggested is the same as this one (link below)? http://www.botm.gov.pl/infomat/MySQLConverterTool/GUI/index.php

For example, it converts this:
[code=php]
$sResult = mysql_query("$sel_com");
[/code]


into this:

[code=php]
$sResult = mysqli_query($GLOBALS["___mysqli_ston"], "$sel_com");
[/code]


Do I still need to write code for MySQLi command to connect to database?
Copy linkTweet thisAlerts:
@rootNov 06.2017 — Besides swapping out the mysql_ for the mysqli_ I need to establish a mysqli connection to the database. Could you please provide some code?

As for the polyfiller function, I have no idea how to write it. As I mentioned above, I'm not a programmer. ?[/QUOTE]

Its going to be like the other functions that are mysql_ converted to mysqli_

If you use an editor like Notepad++ you could open all the files to your website and do a simple find and replace for any mysql_ and replace with mysqli_
Copy linkTweet thisAlerts:
@visitor52authorNov 06.2017 — Use this tool, it will convert whole script into mysqli in seconds - https://github.com/philip/MySQLConverterTool[/QUOTE]

Dear phpmillion, I forgot to ask you. If the MySQLConverterTool you suggested is not the same as the tool I mentioned above, how to run it after I unzip it? I followed the instructions in the ReadMe file but something didn't work... ?
Copy linkTweet thisAlerts:
@benanamenNov 06.2017 — Its going to be like the other functions that are mysql_ converted to mysqli_

If you use an editor like Notepad++ you could open all the files to your website and do a simple find and replace for any mysql_ and replace with mysqli_[/QUOTE]


C'mon Super Moderator, you cannot just throw an i onto the end of mysql.
Copy linkTweet thisAlerts:
@benanamenNov 06.2017 — Dear phpmillion, can you tell me if the converter that you suggested is the same as this one (link below)? http://www.botm.gov.pl/infomat/MySQLConverterTool/GUI/index.php

For example, it converts this:
[code=php]
$sResult = mysql_query("$sel_com");
[/code]


into this:

[code=php]
$sResult = mysqli_query($GLOBALS["___mysqli_ston"], "$sel_com");
[/code]


Do I still need to write code for MySQLi command to connect to database?[/QUOTE]


OP, if that is the code it is spitting out, then stay away from it. There is no magic hack to transform your code. As I told you, you are going to have to do a re-write. It is not just the obsolete mysql code that is wrong with your script.
Copy linkTweet thisAlerts:
@visitor52authorNov 06.2017 — 
If you use an editor like Notepad++ you could open all the files to your website and do a simple find and replace for any mysql_ and replace with mysqli_[/QUOTE]


Yes, that is simple to do. I've been asking about mysqli_connect which requires some $link parameter. Don't I have to establish connection to the database, either in functions.php or some additional file?
Copy linkTweet thisAlerts:
@visitor52authorNov 06.2017 — .. As I told you, you are going to have to do a re-write.[/QUOTE]

benanamen, I got that and I've already asked you a few times - what is wrong in those code snippets I provided? Where to start re-writing what??? Can you be a little more specific please?
Copy linkTweet thisAlerts:
@benanamenNov 06.2017 — I gave you a detailed answer in the "other" forum you posted this too. This is yet another problem from cross-posting the same question to multiple forums. At least five different ones at my last count.
Copy linkTweet thisAlerts:
@rootNov 06.2017 — Spot the difference...
[code=php]$link = mysqli_connect("localhost", "mysql_user", "mysql_password");[/code]
[code=php]$link = mysql_connect("localhost", "mysql_user", "mysql_password");[/code]

So yes, you can throw an 'i' in to it.
Copy linkTweet thisAlerts:
@benanamenNov 06.2017 — Seriously Super Moderator? Your ignorance on this subject is showing.

Here are two basic examples. They are [U]exactly[/U] the same except the second one has an i thrown on the end of mysql_* that you claim is all you have to do. The first one works, the second one does not. So NO, you cannot just throw an i on the end and magically have mysqli. Php itself proves you are wrong.


[code=php]<?php
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
die('Not connected : ' . mysql_error());
}

// make blog the current database
$db_selected = mysql_select_db('test', $con);
if (!$db_selected) {
die ('DB not selected : ' . mysql_error());
}
?>[/code]



[code=php]<?php
$con = mysqli_connect('localhost', 'root', '');
if (!$con) {
die('Not connected : ' . mysqli_error());
}

// make blog the current database
$db_selected = mysqli_select_db('test', $con);
if (!$db_selected) {
die ('DB not selected : ' . mysqli_error());
}
?>[/code]



[B][COLOR="#FF0000"]Warning: mysqli_select_db() expects parameter 1 to be mysqli, string given on line 8[/COLOR][/B]

[B][COLOR="#FF0000"]Warning: mysqli_error() expects exactly 1 parameter, 0 given on line 10[/COLOR][/B]
Copy linkTweet thisAlerts:
@visitor52authorNov 06.2017 — I gave you a detailed answer in the "other" forum you posted this too...[/QUOTE]

You mean your detailed answer in which you stated that you do NOT deal with MySQL? Oh yeah, that is very helpful! This thread is about MySQL, and I don't understand why you even bother posting here. Oh, I forgot that you need to count forums with this thread. Sure, keep counting. I wish you gave at least one line of useful code instead.
Copy linkTweet thisAlerts:
@ginerjmNov 06.2017 — You do realize that this is a forum for those that WANT to be programmers and currently need help with their code. To walk right in and tell us you are not programmer and ask us to fix your scripts is a bit beyond what the people here generally do. We help those who wish to learn. You OTOH do not seem like one who wants to learn so what are you asking for - free labor?

There is another forum on this site that you should visit if you want someone to do your (your company's ?) work for you. I suggest you visit it, work out the goals you have and review their recommendations with a competent programmer and then hire them to do this task for you.

Personally I would skip the conversion from MySQL to mysqli and go directly to PDO. A much better interface. Either path will require more than cosmetic changes and the latter gives you a more long-range solution.

PS - if it has been that long since this code has been updated you are probably several version behind. I am surprised that you haven't run into problems with it before now.
Copy linkTweet thisAlerts:
@benanamenNov 06.2017 — You mean your detailed answer in which you stated that you do NOT deal with MySQL? Oh yeah, that is very helpful! This thread is about MySQL, and I don't understand why you even bother posting here. Oh, I forgot that you need to count forums with this thread. Sure, keep counting. I wish you gave at least one line of useful code instead.[/QUOTE]

OP, DO NOT MISQUOTE ME! I said I don't not mess with Mysql[B][COLOR="#FF0000"][SIZE=4]i[/SIZE][/COLOR][/B] meaning that I code in PDO which any expert programmer "should" be using.

One line of useful code? You are really going to take that attitude? I gave you more than a line of "useful" code. I gave you a direct link to an entire tutorial full of usefull code. You don't even know what to do with code so what point is there in anybody giving you code.

You have two choices, either learn how to program and make an attempt at helping yourself or keep cross- trolling on all the forums hoping someone will just write the thing for you for free.
Copy linkTweet thisAlerts:
@rootNov 06.2017 — [B][COLOR="#FF0000"]Warning: mysqli_select_db() expects parameter 1 to be mysqli, string given on line 8[/COLOR][/B]

[B][COLOR="#FF0000"]Warning: mysqli_error() expects exactly 1 parameter, 0 given on line 10[/COLOR][/B][/QUOTE]


Then I said... "Work the errors". which is plain english for you need to swap the terms in the brackets. a simple find and replace in an editor like Notepad++ using a Regular Expression to find and swap the terms for that problem.

I have recently had this mysqli_ issue with a CMS on a friends site, the vendor no longer exists and I was asked to help debug the problem because the site had gone dark when the host upgraded PHP and the support for mysql_* functions were removed.

What I found under the hood was astonishing, bit frightening in places and I nearly gave myself a hernia laughing at some of the code base... So if you think that my coding is bad, wanna read a comedy?
Copy linkTweet thisAlerts:
@benanamenNov 06.2017 — I was basing my response on your post #8 which read to me like you were saying all you had to do was add an [I]i[/I].
Copy linkTweet thisAlerts:
@phpmillionNov 07.2017 — Dear phpmillion, can you tell me if the converter that you suggested is the same as this one (link below)? [URL]http://www.botm.gov.pl/infomat/MySQLConverterTool/GUI/index.php[/URL]

For example, it converts this:
[code=php]
$sResult = mysql_query("$sel_com");
[/code]


into this:

[code=php]
$sResult = mysqli_query($GLOBALS["___mysqli_ston"], "$sel_com");
[/code]


Do I still need to write code for MySQLi command to connect to database?[/QUOTE]


Yes, it's the same tool. The script converts your code to mysqli, but you may need to modify your config file (or whatever file you connect to MySQL database from) to establish mysqli-based connection.
Copy linkTweet thisAlerts:
@phpmillionNov 07.2017 — visitor52, the tool at [URL]http://www.botm.gov.pl/infomat/MySQLConverterTool/GUI/index.php[/URL] is the same tool I provided a link to.

I don't remember if it modifies MySQL connection details (used it years ago), but if you get any connection errors after converting your script, then yes, you need to modify your config file (or whatever file you establish a database connection from) to match new code. Usually it will be like this:

[code=php]$DB_HOST="";
$DB_NAME="";
$DB_USER="";
$DB_PASS="";


$GLOBALS["___mysqli_ston"]=mysqli_connect($DB_HOST, $DB_USER, $DB_PASS);
mysqli_select_db($GLOBALS["___mysqli_ston"], $DB_NAME);[/code]


As you see, I modified code to match the name of your mysqli link.
Copy linkTweet thisAlerts:
@visitor52authorNov 07.2017 — ....

As you see, I modified code to match the name of your mysqli link.[/QUOTE]


Dear phpmillion, thank you so much! You are the man! I'm really glad that there are people like you in public forums, who are willing to help with a few lines of code needed!
Copy linkTweet thisAlerts:
@visitor52authorNov 07.2017 — ... I gave you more than a line of "useful" code. I gave you a direct link to an entire tutorial full of usefull code. You don't even know what to do with code so what point is there in anybody giving you code....[/QUOTE]

A direct link to a tutorial on PDO??? How is that supposed to help me?! This thread is related to MySQL, not PDO! (if you have not noticed yet) You have not offered any help, any solution, not a single line of code! Instead, you are flooding my thread with your negative, unsubstantiated, unhelpful statements, basically sabotaging it.

I've had enough of you. If you can't help, please do me and everybody else a favor, do not post in my thread any more!
Copy linkTweet thisAlerts:
@ginerjmNov 07.2017 — visitor52,

No - I disagree with you. This thread is related to your desire to get help with CONVERTING a script from the usage of the deprecated MySQL interface to another interface that is more current. That is the topic. That, and your inability to see what people are trying to help you do which is to move to a more modern approach and skip what you think is a very simple thing to do. If it were so simple, then why would you need us?

Apparently benanamen has viewed other forums where you have posted similar questions. Have you not addressed them? He seems to be frustrated with whatever conversations you have had on those sites which leads me to think that you are very difficult to work with. Why do you not just stick to one place and attempt to work WITH those that are attempting to help you?

With you not being a programmer we are very, very limited in what we can tell you to do since you don't comprehend what has been said so far. That may be because you have no .... idea what has to be done but think you do. If you were not mechanically inclined how do you think we could possibly tell you how to change the oil in your car?

Either accept responsibility for your task and do some serious learning (aka, reading) and get on board with this project and this forum's offers of help. Do NOT expect the people here to re-write your script. If that is what you are expecting it's time to look for paid help as I suggested earlier. The people here (again) are way more than helpful to those who are trying but there is a line between those who are trying and those who can't. In the not-so-long-ago past I also was a newbie and was helped many times here during my learning process.

Sorry to be so blunt and I know that I risk triggering another rant from you. I can take it though.
Copy linkTweet thisAlerts:
@visitor52authorNov 07.2017 — ...We help those who wish to learn. You OTOH do not seem like one who wants to learn so what are you asking for - free labor?

PS - if it has been that long since this code has been updated you are probably several version behind. I am surprised that you haven't run into problems with it before now.[/QUOTE]


I did not say I didn't wish to learn. What do you think I'm doing while trying to update my script? And if you look at my questions, you will notice that I'm not asking for re-writing the entire script for me. Why are you exaggerating?! What I asked for comes basically to a few lines of code establishing MySQLi connection to a database so I could replace mysql_escape_string() with mysqli_real_escape_string(). Is this a huge "labor"?! The old simple (for professional) script has been working so far and requires only replacement of deprecated MySQL functions which can be achieved by literally changing or adding just a few lines of code. This is why I came to the forum and asked for help. And guess what, there are good people here who simply help and do not "sermonize" anyone.

I wonder if you aware that there are all kinds of people turning to forums for help. Not all of them are programmers or want to be programmers. You seem to be against that and keep only "programmers" on this forum? Well, dude, this is called "discrimination".

Please keep in mind that this thread (related to MySQL) might help not only many others like me being in similar dare situation, but also beginner-programmers as you would like it I suppose. So if you can help, please do!
Copy linkTweet thisAlerts:
@ginerjmNov 07.2017 — I have to wonder what you are doing between posts. It could not possibly be learning about the changes that have to be done to this script. Your shortage of knowledge is apparent in your statement that all you want is help changing your connection logic in order to switch a SINGLE statement from the use of MySQL_escape_string to mysqli_real_escape_string. That is ludicrous. You have to change every MySQL_* function to a mysqlI_* function. and perhaps re-organize some other processes that may be occurring in the script to access the data results.

I rest my case. Good luck.
Copy linkTweet thisAlerts:
@NogDogNov 07.2017 — Closing thread, as I've had enough of all the chest-thumping.

Sorry to the OP. If you have further specific questions regarding the suggestion you received, please open a separate thread to address it. Those of you who feel that it's the wrong solution, just move on to another thread where you have something constructive to contribute.
×

Success!

Help @visitor52 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...