Why isn't mysql_real_escape_string working? - php

I am trying to insert a ' symbol into my database and have the below code.
$actionurl =$_POST['actionurl'];
$newtitle = $_POST['newtitle'];
$newtitle = mysql_real_escape_string($newtitle);
$result2 = mysql_query("UPDATE links SET title='$newtitle' WHERE url='$actionurl'")
or die(mysql_error());
And I get this error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's to start up a sample library (forum thread)'' at line 1
Why am I getting an error if I'm using mysql_real_escape_string on the $newtitle variable?

I suspect that it's actionurl that is causing the error, not $newtitle.
To debug this, echo or print the SQL statement to be executed.
You can do something like this:
$sql = "UPDATE links SET title='$newtitle' WHERE url='$actionurl'";
// for debugging, output contents of the $sql string
echo "SQL=" . $sql ;
mysql_query($sql) or die(mysql_error();
As others have already suggested, the mysql_ interface is deprecated. New development should use either mysqli or PDO. And use prepared statements with bind placeholders. It just seems nonsensical to be struggling with mysql_real_escape_string in 2016.

Are magic quotes on in your php.ini? If yes, disabling it should solve your issue. (It could be enabled by default)

Related

The right syntax for insertion into Mysql using php

I'm trying to insert some values into the database using information posted on a form through php
following is the code that i'm using for insertion
$query=mysql_query("select * from poll_question where question = '$question'") or die(mysql_error());
$numrows=mysql_num_rows($query);
if($numrows)
{
while($row=mysql_fetch_assoc($query))
{
$dbid=$row['id'];
}
}
$sql1 = "INSERT INTO poll_option(option , poll_id ,click)
VALUES('$_POST[optionone]',
'$dbid' , 0)";
$result1 = mysql_query($sql1);
echo "1 record added";
echo mysql_error();
$sql2 = "INSERT INTO poll_option(option , poll_id , click)
VALUES('$_POST[optiontwo])',
'$dbid', 0)";
$result2 = mysql_query($sql2);
echo mysql_error();
$sql3 = "INSERT INTO poll_option(option , poll_id, click)
VALUES('$_POST[optionthree])',
'$dbid ', 0)";
$result3 = mysql_query($sql3);
echo mysql_error();
now i'm getting the following output
You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near 'option , poll_id ,click) VALUES('sj', '24' , 0)' at line 1
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'option , poll_id , click) VALUES('dsdg', '24', 0)' at line 1
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'option , poll_id, click) VALUES('xzf', '24 ', 0)' at line 1
The part under the "values" syntax is the one that i'm trying to insert. that information is correct.that is VALUES('xzf', '24 ', 0) is Correct and i want to insert this only , but their is some problem with the syntax.Any suggestions?
What echo_me said.
Additionally, in $sql2 and $sql3 you are closing the VALUES (...) parenthesis too soon:
VALUES('$_POST[optiontwo])',
^ remove this
Your $sql1 is correct.
OPTION is reserved keyword for mysql
try use backticks around it in all your queries
like that:
`option`
look reserved keywords here
In addition to what echo_me stated in removing the parentheses incorrectly added to $sql2 and $sql3, you really should migrate over to mysqli (since mysql is deprecated) and at least use the real escape string option on your post variable before automatically inserting whatever is posted to the script into your database. A good example for your code is:
$post_option1 = mysql_real_escape_string($_POST['optionone']);
$post_option2 = mysql_real_escape_string($_POST['optiontwo']);
$sql1 = "INSERT INTO poll_option (`option`, `poll_id`, `click`) VALUES('$post_option1', '$dbid', 0)";
$sql2 = "INSERT INTO poll_option (`option`, `poll_id`, `click`) VALUES('$post_option2', '$dbid', 0)";
My opinion is it would make things simpler for you as well. The info on the real escape string can be found here:
http://php.net/manual/en/function.mysql-real-escape-string.php
It's against best practice to insert a POST or GET directly into your database without any form of mitigation against SQL injection.
Try to avoid using mysql functions, but rather learn to use PDO functions. They have a number of advantages over mysql functions, although im really sorry, i dont remember them right now, and i dont want to say anything that's not true.
Also, i dont think that the mysql functions can prevent SQL injection, which can let any user alter your Database however they want.
Most importantly though, is that they're deprecated in PHP 5.5
Sorry if i didn't solve your question, just thought to let you know. Good luck, maybe you can get it to work with the new functions.
Update: Sorry, didn't see the comments and posts about switching to mysqli and such.

Mysql syntax error in php query not showing up in browser

Let's say that I have an error in a php/mysql query :
$query = "SELECT * ROM users WHERE _id = :user_id";
Here, FROM is missing an "F".
When I launch this php file in localhost, my browser is not reacting, it should display something like that:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
But it doesn't, only blank page...
How do I enable this option?
EDIT: I'm using PDO.
If you use mysql_* functions you have to do something like: mysql_query($sql) or die(mysql_error());
If you use mysqli_*: mysqli_query($sql) or die(mysqli_error());
If you use PDO: $stmt->execute() or die(print_r($stmt->errorInfo)); //$stmt is instance of PDOStatemen
If you still use mysql_* I strongly recommend to stop using (sql injection I mean).
First use mysql_error() function in your code in case if query is not executed
successfully. something like this :
if(!mysql_query($query)){
echo mysql_error();
}
Secondly, check in your php.ini whether error_reporting is on or off.
Then check on the browser for the error.

SQL error when deleting from MySQL

I am coming across a problem when deleting data from my SQL data. I have tried various versions of my statement but to no avail. Below is the error I am presented with and the statement I am using.
$sql = "DELETE FROM `saved_holidays` WHERE (subscriberID= $user AND title= $check_value)";
//connect to database then execute the SQL statement.
$db->exec($sql);
and the error message is:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near '#xml119.com AND
title= Luxurious Jamaican holidays | 40% Discount On Accommodati' at
line 1
I can see that the correct data is being passed but the syntax is wrong. Can anyone help?
$check_value is a string, so you have to enclose it in ' in your query like this:
title = '$check_value'
For security purposes, you should also use mysql_real_escape_string on all string parameters you have. Or even better, use prepared statements: http://php.net/manual/en/pdo.prepared-statements.php
You need to put quotations around your variables. It doesn't like spaces.
Depending on the server you are using (MySQL or MSSQL) you have to use backticks, single quotes, or double quotes:
DELETE FROM saved_holidays WHERE (subscriberID="$user" AND title="$check_value")
Also, if you are using PDOs, you should consider using prepared statements:
$statment = $conn->prepare("DELETE FORM saved_holidays WHERE (subscriberID=? AND title=?)"); //$conn has to be your connection ceated by doing new PDO(...connection string...)
$statment->execute(array($user, $check_value));
Amit is correct your statement should look like this;
$sql = "DELETE FROM `saved_holidays` WHERE (subscriberID= '$user' AND title= '$check_value')";
the variable is a string so must be enclosed in single quotes.
This should then work for you.

mysql_real_escape_string() not sanitizing variable

I'm working on an existing website trying to prevent SQL injections. Before $_GET['ID'] was unsanitized.
$ID=mysql_real_escape_string($_GET['ID']);
$sQuery=mysql_query("select * from tbl_mini_website as s1, tbl_actor_merchant as me where s1.MERCHANT_ID=$ID AND s1.MERCHANT_ID=me.MERCHANT_ID");
If I put a ' at the end of the url, with mysql_real_escape_string() I get this from mysql_error():
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\\' AND s1.MERCHANT_ID=me.MERCHANT_ID' at line 1
with out mysql_real_escape_string() I get:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\' AND s1.MERCHANT_ID=me.MERCHANT_ID' at line 1
I'm not sure whats up with it? Any help would be greatly appreciated.
If it is an id, numerical I assume, why don't you just cast it to an integer?
$ID = (int) $_GET['ID'];
The best advice I can give you is to check out PDO and use bound parameters.
mysql_real_escape_string escapes, but doesn't quote.
Try:
$sQuery=mysql_query("select * from tbl_mini_website as s1, tbl_actor_merchant as me where s1.MERCHANT_ID='$ID' AND s1.MERCHANT_ID=me.MERCHANT_ID");
More generally, I tend to wrap both of these in a function, like:
function quoteValue($value) {
return "'" . mysql_real_escape_string($value) . "'";
}
This is useful, because you may find down the line that you want more refined quoting behavior (especially when it comes to handling Unicode, control characters, etc.)
It's because you're not quoting the variable.
Here's your query given the following inputs
$_GET['ID'] = "1";
$ID=mysql_real_escape_string($_GET['ID']);
SELECT ... where s1.MERCHANT_ID=1 ...
$_GET['ID'] = "1'"
$ID=mysql_real_escape_string($_GET['ID']);
SELECT ... where s1.MERCHANT_ID=1\' ...
$_GET['ID'] = "1'"
SELECT ... where s1.MERCHANT_ID=1' ...
Phil Brown is right, but you shoul forget about old fashioned mysql_real_escape_string or mysql_connect() as they are very old and move to php`s PDO() where you cand use prepared statements, binds, fetch object any many many more functions.
I suggest read PDO documentation at http://php.net/manual/en/book.pdo.php if you want next generation dabatase manipulation and security from SQL Injection .

Error in MySQL update command. (in php)

Good Morning everyone,
I am using an update command in php to update data in mysql. This is my code:
$sql=mysql_query("UPDATE blpublication SET JournalName = '$_POST[journal]', AcceptanceDate = '$_POST[acceptancedate]', PublishedDate = '$_POST[publisheddate]', Comment = '$_POST[comment]'
WHERE JobNo = '$_POST[jobno]'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "record Updated";
It does updates the field but, it gives me the following error. And i can not figure it out why am i getting this error.
"Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1"
Can you help me in this
Best
Zeeshan
Can you tell us what the exactly output of $sql is? By the way, BIG security hole there. You should always escape query inputs namely:
$journal = mysql_real_escape_string($_POST['journal']);
$acceptance_date = mysql_real_escape_string($_POST['acceptancedate']);
$publish_date = mysql_real_escape_string($_POST['publisheddate']);
$comment = mysql_real_escape_string($_POST['comment']);
$job_no = intval($_POST['jobno']); // assuming jobNo is a number
$sql = <<<END
UPDATE blpublication
SET JournalName = '$journal',
AcceptanceDate = '$acceptance_date',
PublishedDate = '$publish_date',
Comment = '$comment'
WHERE JobNo = $jobno
END;
mysql_query($sql);
if (mysql_error()) {
die("Error executing query '$sql': " . mysql_error());
}
echo "record Updated";
I would sanitize your input first. This could lead to some very nasty errors such as what you are experincing and malicious attacks. Look up SQL Injection.
I think the problem is that you're running mysql_query twice. The first time it works and returns 1 (true), which you assign to $sql. Then you call mysql_query again, passing $sql (which equals 1). Of course "1" is not a valid SQL query, so you get the syntax error.
I wholeheartedly agree that you must sanitize those inputs!
Similar to the following post, i believe when you have any object or array syntax, you need to put in braces.
SET JournalName = '${_POST[journal]}'
edit: and yes, as others pointed out you are risking sql injection.
First of all, your code is prone to SQL injection, escape your POST values:
$journal = mysql_real_escape_string($_POST['journal']);
And to actually debug your query, we need the query itself. Add an echo() statement before the actual execution of the query and post the result, the POST values possibly contain some unexpected value.
Your general UPDATE syntax looks ok, except for the obvious injection possibilities, but you need to output $sql. One of your variables probably has a quote in it or some other issue like that....
Looking at the SQL UPDATE statement in your code, one thing leaps out at me. The table name is blpublication, are you maybe missing a 't', i.e. tblpublication?
Also you should really sanitise your input, otherwise you're going to be a victim of a SQL injection attack.
Try concatenating the $_POST values. Im not sure if including them without quoting the key is possible?
$sql= mysql_real_escape_string("UPDATE blpublication SET JournalName = '".$_POST['journal']."', AcceptanceDate = '".$_POST['acceptancedate']."', PublishedDate = '".$_POST['publisheddate']."', Comment = '".$_POST['comment']."'
WHERE JobNo = '".$_POST['jobno']."'");
$result = mysql_query($sql);
Note: mysql_* commands are depreciated. You should switch over to mysqli_*.

Categories