single quotes in SQL Query - php

Im writing a php script that is used to update a database but it is giving errors when i tries to run the query it returns an error along the lines of
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 'id=15"' at line 1
Where it says "To use near" seems to display part of the query after there is a space in the data. Im assuming i need to put single quotes around where the data to the query from the php variables but when i try to put them in (even escaping the quotes) i get parse errors from the script
The SQL Query is
mysql_query("UPDATE Videos SET Title=".$_POST['Title'].", Preacher=".$_POST['Preacher'].", Date=".$_POST['Date'].", Service=".$_POST['Service'].", File=".$_POST['File'].", Description=".$_POST['Description']."WHERE id=".$_GET['vid_id']."\"") or die(mysql_error());
Thank in advance for any help

mysql_real_escape_string() and sql injections have already been mentioned.
But right now your script (painstakingly) has to mix the sql statement with the data/parameters and in the next step the MySQL server has to separate the data from the statement.
Using (server-side) prepared statements both "parts" of your query are sent separately and the sql parser (of your MySQL server) can never get "confused" about where the statement ends and the data begins.
The php-mysql module doesn't know prepared statements but php-mysqli and PDO do.
$pdo = new PDO('mysql:host=localhost;dbname=test', '...', '...');
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $pdo->prepare('
UPDATE
Videos
SET
Title=:title ,
Preacher=:preacher ,
Date=:date ,
Service=:service ,
File=:file ,
Description=:description
WHERE
id=:id
');
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':preacher', $_POST['preacher']);
$stmt->bindParam(':date', $_POST['date']);
$stmt->bindParam(':service', $_POST['service']);
$stmt->bindParam(':file', $_POST['file']);
$stmt->bindParam(':description', $_POST['description']);
$stmt->bindParam(':id', $_GET['id']); // really _GET?
$stmt->execute();
May seem a lot of bloat if you use $stmt for only one operation. But consider that otherwise you have to call mysql_real_escape_string() for each parameter.

You need to escape the variables properly and surround them by single quotes:
mysql_query("UPDATE
Videos
SET
Title = '".mysql_real_escape_string($_POST['Title'])."',
Preacher = '".mysql_real_escape_string($_POST['Preacher'])."',
Date = '".mysql_real_escape_string($_POST['Date'])."',
Service = '".mysql_real_escape_string($_POST['Service'])."',
File = '".mysql_real_escape_string($_POST['File'])."',
Description = '".mysql_real_escape_string($_POST['Description'])."'
WHERE
id = '".mysql_real_escape_string($_GET['vid_id'])."'")
or die(mysql_error());
Without escaping your variables properly, you are making yourself vulnerable to SQL injection attacks.
EDIT
To simplify the above, you can do a few tricks:
// Apply mysql_escape_string to every item in $_POST
array_map('mysql_real_escape_string', $_POST);
// Get rid of $_POST, $_POST['Title'] becomes $p_Title
extract($_POST, EXTR_PREFIX_ALL, 'p_');
// Use sprintf to build your query
$query = sprintf("UPDATE
Videos
SET
Title = '%s',
Preacher = '%s',
Date = '%s',
Service = '%s',
File = '%s',
Description = '%s'
WHERE
id = '%s'",
$p_Title,
$p_Preacher,
$p_Service,
$p_File,
$p_Description,
mysql_real_escape_string($_GET['vid_id']));
mysql_query($query) or die(mysql_error());
Note that mixing $_POST and $_GET variables is not encouraged. You should supply the update ID through an hidden input field in the form.

As you are using DB API directly (no DB abstraction level) the best solution is to use DB escape function.
Just use mysql_real_escape_string().
<?php
// Your query
$query = sprintf("UPDATE Videos SET Title='%s', preacher='%s', Date='%s', "
."Service='%s', File='%s', Description='%s' WHERE id='%s'",
mysql_real_escape_string($_POST['Title']),
mysql_real_escape_string($_POST['Preacher']),
mysql_real_escape_string($_POST['Date']),
mysql_real_escape_string($_POST['Service']),
mysql_real_escape_string($_POST['File']),
mysql_real_escape_string($_POST['Description']),
mysql_real_escape_string(($_GET['vid_id']));
?>
As a bonus you'll get a really improved security against SQL INJECTION attacs your previous code was prone.
In the case you would simply escape slashes you have, again, to use php/mysql functions addslashes() will do the job in this case.

Why are you putting a \" right at the end, this puts a " on to the end of your SQL but you don't have one at the start?
Try this:
mysql_query("UPDATE Videos SET Title=".$_POST['Title'].", Preacher=".$_POST['Preacher'].", Date=".$_POST['Date'].", Service=".$_POST['Service'].", File=".$_POST['File'].", Description=".$_POST['Description']."WHERE id=".$_GET['vid_id']) or die(mysql_error());

REMOVE \", from:
id=".$_GET['vid_id']."\""

Related

MySQL syntax error?

I'm using a developer to help me build a site - and I'm getting an error relating to a webform when I use the text: I'm
Further details:
“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 'm', team_member_pic = ''' at line 7”
that he can't solve. He's suggesting it's the version of MySQL (5.5.23) on my webhost (Hostgator) - because the code seems to work okay on his server with MYSQL 5.5.xx at (GoDaddy)
The code he's applying is as follows:
$insert = "INSERT INTO ".TABLE_PREFIX."host_manager_team_members SET
user_id = '".$_REQUEST['id']."',
team_member_firstname =
'".addslashes($_REQUEST['team_member_firstname'])."',
team_member_surname =
'".addslashes($_REQUEST['team_member_surname'])."',
team_member_email =
'".addslashes($_REQUEST['team_member_email'])."',
team_member_phone =
'".addslashes($_REQUEST['team_member_phone'])."',
team_member_desc =
'".mysql_real_escape_string($_REQUEST['team_member_desc'])."',
team_member_pic = '".$filepath."'";
mysql_query($insert) or die(mysql_error());
Can anyone give some guidance on what could be causing this error? Would really appreciate any thoughts/ideas you would have.
Use sprintf like this
$insert = sprintf("INSERT INTO ".TABLE_PREFIX."host_manager_team_members SET
user_id = '%s',
team_member_firstname =
'%s',
team_member_surname =
'%s',
team_member_email =
'%s',
team_member_phone =
'%s',
team_member_desc =
'%s',
team_member_pic = '%s'",$_REQUEST['id'],addslashes($_REQUEST['team_member_firstname']),addslashes($_REQUEST['team_member_surname']),addslashes($_REQUEST['team_member_email']),addslashes($_REQUEST['team_member_phone']),mysql_real_escape_string($_REQUEST['team_member_desc']),$filepath);
mysql_query($insert) or die(mysql_error());
Your code is just about as vulnerable as it can be:
Don’t use $_REQUEST, as you don’t know where the data is coming from. It is a combination of $_GET, $_POST and $_COOKIE, and it makes it very easy for a user to inject their own additional data by simply appending ?evilstuff=hahaha to the URL.
Don’t use mysql_ functions. They are deprecated and removed in PHP7. That’s good because MySQL4, for which the original functions were created, did not have the more secure features implemented later.
Don’t use addslashes. It a poor attempt to escape strings against the possibility of SQL injection. If you must do it the old way, use one of the real_escape_string functions. Better still:
Always use prepared statements when accommodating user data. Preparing the statement results in interpreting the SQL before data has been injected, so any additional data, even if it looks like SQL, will be treated as pure data only.
Finally,
It is much easier to use PDO, which has been available since PHP 5.
Here is an alternative using PDO & prepared statements:
$table=TABLE_PREFIX.'host_manager_team_members';
$insert = "INSERT INTO $table SET user_id = ?, team_member_firstname = ?,
team_member_surname = ?, team_member_email = ?, team_member_phone = ?,
team_member_desc = ?, team_member_pic = ?";
$prepared=$pdo->prepare($insert);
$prepared->execute(array(
$_REQUEST['id'],
$_REQUEST['team_member_firstname'],
$_REQUEST['team_member_surname'],
$_REQUEST['team_member_email'],
$_REQUEST['team_member_phone']
$_REQUEST['team_member_desc'],
$filepath
));
The SQL statement is much easier to debug when you can see it by itself.
Note that you do not put quotes around the string values in a prepared statement. This is because quotes are only required for strings when they are constructed in code. By the time the prepared statement gets the data, the string has already been constructed.
I have also used a double quoted string to allow the interpolation of a variable which is not user-generated.
I see that you’re using a quirky MySQL extension to the INSERT statement, which is by no means universally supported. Perhaps you should try the more standard syntax:
$insert = "INSERT INTO $table user_id (team_member_firstname,
team_member_surname, team_member_email, team_member_phone,
team_member_desc, team_member_pic)
VALUES(?,?,?,?,?,?)";
Finally, to answer your question, it is quite possible that the error is caused by the data itself. What you need to do is print the contents of your string generated string, and then run that though MySQL directly (possibly using the SQL tab in PHPMySQL).
So, even without doing any of the above, you should try:
print $insert;
exit;
Perhaps you could try this and post the results here.

writing data into mysql with mysqli_real_escape_string() but without &

iam using this code below, but the character "&" will not be inserted into the db, also when i copy/paste some text from other pages and put it into the db the text ends for example in the middle of the text, dont know why, i tried also addslashes() and htmlspecialchars() or htmlentities().
i read mysqli_real_escape_string() is againt SQL injection attacks and htmlspecialchars() against XSS attachs, should i also combine them ?
$beschreibung = mysqli_real_escape_string($db, $_POST['beschreibung']);
SQL Injection is merely just improperly formatted queries. What you're doing is not enough, stop now. Get into the practice of using prepared statements..
$Connection = new mysqli("server","user","password","db");
$Query = $Connection->prepare("SELECT Email FROM test_tbl WHERE username=?");
$Query->bind_param('s',$_POST['ObjectContainingUsernameFromPost']);
$Query->execute();
$Query->bind_result($Email);
$Query->fetch();
$Query->close();
Above is a very basic example of using prepared statements. It will quickly and easily format your query.
My best guess to what is happening, I'm assuming you're just using the standard:
$Query = mysqli_query("SELECT * FROM test_tbl WHERE Username=".$_POST['User']);
As this query is not properly formatted you may have the quotes in your chunk of text which close the query string. PHP will then interpret everything as a command to send to the SQL server
If you know what you are doing, you can escape indata yourself and add the escaped data to the query as long as you surround the data with single quotes in the sql. An example:
$db = mysqli_connect("localhost","my_user","my_password","my_db");
$beschreibung = mysqli_real_escape_string($db, $_POST['beschreibung']);
$results = mysqli_query(
$db,
sprintf("INSERT INTO foo (beschreibung) VALUES ('%s')", $beschreibung)
);
To get predictable results, I advise you to use the very same character encoding, e,g, UTF-8, consistently through your application.

Apostrophy and quotation marks won't add to mysql from a form

I need some help here!
I have a form on a site admin page, the owner fills in his projects and the get added to a mysql db, but sometimes the data contains single or double quotes so it won't add to the db.
I tried using addslashes but it still wont work.
Heres my code which Ive tried
$atitle = addslashes($_REQUEST['atitle']);
$acontent = addslashes($_REQUEST['acontent']);
$query = "INSERT INTO projects VALUES (NULL, '$atitle', '$acontent', '$remote_file', '$remote_file1', '$remote_file2')";
$result = mysql_query($query);
if(!$result){
$error = 'An error occured: '. mysql_error().'<br />';
$error.= 'Query was: '.$query;
echo $error;
die($message);
}
Can anyone help me with this?
mysql_query is part of an outdated php library that isn't supported anymore. The more reliable method of interacting with a database is mysqli. Using mysqli, you'll be able to use Prepared Statements. Prepared Statements are a way to validate input and to mitigate problems like this (your input having quotation ticks/marks). Take a look at this example:
$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("INSERT INTO projects VALUES (NULL, '?', '?', '?', '?','?')");
$stmt->bind_param('s', $atitle); // s means string in the first param
$stmt->bind_param('s', $acontent); // s means string in the first param
... // same for all other parameters in your query
$stmt->execute();
More on this: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
I heavily recommend using mysqli. It is current and supported. Prepared Statements are the best way to defend against SQL injections and also catching trip-ups like this. It will sanitize the input for you and account for quotation symbols.
you can try stripslashes() to un-quotes a quoted string. More details are available on the PHP documentation website here.

Update SQL query - Set values to PHP string variable

This is probably a very trivial question but I've been struggling with it for a while and also tried finding answers online and still getting errors.
Trying to write a simple UPDATE query for a PHP/MySql form:
$sql="UPDATE mytable SET numericValue = '".$someid."', description = '".$sometext."' WHERE id='".$myid."' ";
Whilst all numeric values are being passed and updated fine, I can't get the description right. The description column is a VARCHAR and $sometext is a string and I cant get it escaped / wrapped with quotes correctly.
You should make use of sprintf, it avoids string confusion by providing placeholders (%d for decimals, %s for strings). See the manual for more.
$sql= sprintf("UPDATE mytable SET numericValue = %d, description = '%s' WHERE id = %d", $someid, $sometext, $myid);
If $someText is coming from GET/POST/.. you should wrap a mysql_real_escape_string() around it to prevent SQL injection (or use PDO prepared statements).
$sql="UPDATE mytable SET numericValue = '$someid' , description = '$sometext' WHERE id='$myid' ";
I think you have to worry about sql injection.

Mysql + php with special characters like '(Apostrophe) and " (Quotation mark)

I have been struggling with a small problem for a while. It's been there for years but it's just been an irritating problem and not a serious one, and I have just worked around it. But now I want to find out if anyone can help me. I have done some google'ing but no success.
If I do a form post from a html textarea in a php file like this:
<form action="http://action.com" method="post">
<textarea name="text">google's site</textarea>
</form>
and of course there is a submit button and so on.
The value is the problem: google's site The value of the textarea have both "(Quotation mark) and '(Apostrophe).
To save this in a mysql_database I do this:
$result = mysql_query("INSERT INTO `table` (`row1`) VALUES ('".$_POST['text']."') ") or die(mysql_error());
And now I get the 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 's site'' at line 1
Your sql string will be:
INSERT INTO `table` (`row1`) VALUES ('google's site')
Which is not a valid statement. As Nanne wrote, escape the string at least with mysql_real_escape_string : http://php.net/manual/en/function.mysql-real-escape-string.php
And read about sql injection
http://en.wikipedia.org/wiki/SQL_injection
Think a bit: if someone posts this: $_POST['text'] with value: ');delete from table;....
Your can say good bye to your data :)
Always filter/escape input!
EDIT: As of PHP 5.5.0 mysql_real_escape_string and the mysql extension are deprecated. Please use mysqli extension and mysqli::escape_string function instead
Always at least use mysql_real_escape_string when adding user-provided values into the Database. You should look into binding parameters or mysqli so your query would become:
INSERT INTO `table` (`row1`) VALUES (?)
And ? would be replaced by the actual value after sanitizing the input.
In your case use:
$result = mysql_query("INSERT INTO `table` (`row1`) VALUES ('".mysql_real_escape_string($_POST['text'])."') ") or die(mysql_error());
Read up on SQL Injection. It's worth doing right ASAP!
Escape the string :D
http://php.net/manual/en/function.mysql-real-escape-string.php
you can use addslashes() function. It Quote string with slashes. so, it will be very useful to you when you are adding any apostrophe in your field.
$result = mysql_query("INSERT INTO `table` (`row1`) VALUES ('".addslashes($_POST['text'])."') ") or die(mysql_error());
instead of using the old mysql* functions, use PDO and write parameterized queries - http://php.net/pdo
I was also Struggling about characters when I was updating data in mysql.
But I finally came to a better answer, Here is:
$lastname = "$_POST["lastname"]"; //lastname is : O'Brian, Bran'storm
And When you are going to update your database, the system will not update it unless you use the MySQL REAL Escape String.
Here:
$lastname = mysql_real_escape_string($_POST["lastname"]); // This Works Always.
Then you query will update certainly.
Example: mysql_query("UPDATE client SET lastname = '$lastname' where clientID = '%"); //This will update your data and provide you with security.
For More Information, please check MYSQL_REAL_ESCAPE_STRING
Hope This Helps
Just use prepared statements and you wouldn't have to worry about escaping or sql injection.
$con = <"Your database connection">;
$input = "What's up?";
$stmt = $con->prepare("insert into `tablename` (`field`)values(?)");
$stmt->bind_param("s",$input);
$stmt->execute();
If you are using php version > 5.5.0 then you have to use like this
$con = new mysqli("localhost", "your_user_name", "your_password", "your_db_name");
if ($con->query("INSERT into myCity (Name) VALUES ('".$con->real_escape_string($city)."')")) {
printf("%d Row inserted.\n", $con->affected_rows);
}

Categories