Proper quotation in mysqli_query - php

There some problem in my query.
$test = "Don't look at me";
mysqli_query("INSERT INTO testtable SET testfield = '".$test."' ");
Notice there is a single quote on the string. When I execute it, it returns an error like
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 't look at me ... If I remove the single quote in the string, it works fine. So how can I save the string into the database without removing the single quote?

You can use mysqli_real_escape_string(). It is secures and also prevent your query with sql injection. also your table name and column name in backtick
$test = "Don't look at me";
$val=mysqli_real_escape_string($con,$test); //here you can pass your connection variable
mysqli_query("INSERT INTO `testtable` SET `testfield` = '".$val."' ");
Read Documemt mysql_real_escape_string()

You need to escape them properly-
$test = "Don\'t look at me";
or use aadslashes()
"INSERT INTO testtable SET testfield = '" .addslashes($test). "'"

Or you can use
mysqli_real_escape_string(connection,escapestring)
mysqli_real_escape_string() function escapes special characters in a string for use in an SQL statement.

You should not try to escape values by yourself. Use prepared statements for that: http://php.net/manual/en/mysqli.prepare.php ,
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

Related

MySql error while string is escaped already?

Why this:
$query = "SET NAMES 'utf8'";
$query = str_replace("'", "\'", $query);
$pdo->query($query);
Would cause problem?
I'm currently getting 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 '\'utf8\''
If I don't escape it, everything's fine, but the problem exists with further queries!
The sql you are trying to run is perfectly safe as is, it contains no user input and as such can be run without escaping.
Also you are actually escaping the delimiters of a string, not the value of the string itself.
You don't have to escape every single quote in a query, some are valid such as:
UPDATE table SET field='blah' WHERE id=10
Where field would be a varchar or similar. You would escape the quotes if they need to be part of the value of the field, such as:
UPDATE table SET field='This \'value\' uses quotes.' WHERE id=10
Hope that makes sense.

How would you enter special characters into MySQL from PHP?

Effectively, what I am attempting to do is enter a string similar to this string
into MySQL (it's one line, made into two for readability)
fill:#0000ff;fill-rule:evenodd;stroke:#000000;stroke-width:1px;
stroke-linecap:butt;stroke- linejoin:miter;stroke-opacity:1
MySQL allows me to INSERT the string into the field using phpMyAdmin and phpMyAdmin adds the field as (again one line, made into two for readability):
('fill:#0000ff;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-
linecap:butt;stroke-linejoin:miter;stroke-opacity:1'' in ''field list')
With my PHP code I attempted to add the in field list part to my code as follows
$rectangle_array[$rstyle] = $rectangle_array[$rstyle] . "' in ''field list'";
$mysql_rectangle_table_entry = "INSERT INTO $mysql_table VALUES
($rectangle_array[$rstyle], 'rect',
$rectangle_array[$rid], $rectangle_array[$rwidth],
$rectangle_array[$rheight], $rectangle_array[$rx],
$rectangle_array[$ry])";
$run = mysql_query($mysql_rectangle_table_entry) or die(mysql_error());
And upon running the code I receive the following 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 ':#0000ff;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;s' at line 1
What can I do to make this work?
As noted in the comments…
You could use mysql_real_escape_string() to escape any MySQL special characters before insertion.
For example:
$sql = "INSERT INTO my_table (string_column) VALUES ('" . mysql_real_escape_string($string) . "')";
Another option is to use Prepared Statements with PHP's MySQLi or PDO.
You might want to have a look either at prepared statements or mysql_real_escape_string to escape special characters that might break your INSERT.

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 Query not inserted when PHP variable contains single quotes

This query not inserted when variable $subject has single quotes . Is there any possible solution available ?
mysql_query("INSERT INTO table (to_email_id,subject) values('$to','$subject');");
Consider using Parameterized Queries using PDO for example.
Alternately, enclose your variables in brackets { }.
Edit:
I missed that your variable $subject contains single quotes. This means you have to escape them. (See the myriad of other answers and mysql_real_escape_string() about this.) But as you can see, single quotes inside the variable is exactly how injection attacks work. Escaping them helps prevent such problems as well as allow your query to store the expected data.
No answer about injection attacks is complete without referencing Bobby Tables.
Escape your parameters.
$to = mysql_real_escape_string($to);
$subject = mysql_real_escape_string($subject);
mysql_query("INSERT INTO table (to_email_id, subject) values('$to', '$subject');");
Manual: mysql_real_escape_string()
Also, please read about SQL injection attacks.
Your query will be returning a 1064 error which is a syntax error within your query. This is happening because the variables, specifically $subject in the case of the question is altering the format of your enclosed string. For example, let's say we have
$subject = "fire's hotter than it looks";
When this is evaluated in your query your query string will be
INSERT INTO table (to_email_id,subject)
VALUES('the value of the to variable','fire's hotter than it looks');
If you look at the second item in the values, which was once $subject, you'll notice you now have an uneven number of apostrophes meaning that the end of your query '); is an open string.
As commented above use a function such as mysql_real_escape_string() to add the missing slashes.
Quick note: adding slashes to characters such as " and ' (\", \'). tells mysql to interpret these as string characters instead of query string delimiters.
You need to use mysql_real_escape_string() on your values $to and $subject
Also if you weren't doing this before you are open to sql injection
USE
mysql_real_escape_string
Your query has a great "hole" -> SQL injection. You should read more about this here: http://en.wikipedia.org/wiki/SQL_injection and also here http://php.net/manual/en/function.mysql-real-escape-string.php
To make a short answer you must "escape" values passed to mysql. Best way to do it is with using mysql_real_escape_string function.
$query = sprintf("mysql_query("INSERT INTO table (to_email_id,subject) values('%s', '%s');", mysql_real_escape_string($to),mysql_real_escape_string($subject));
mysql_query($query);
I hope this will help you.
if you are using
(all book's are available) as $subject and you are trying to insert in to mysql
use this
$disc_str = addslashes($subject);
"INSERT INTO table name (subject) value('$disc_str')";
it works for me in Textarea with tinymce also
Solution is very simple. Just add below method before storing your data into php variable
$connection = mysqli_connect($host,$dbuser,$dbpass,$dbname);
$to= mysqli_real_escape_string($connection, $old_email);
$subject= mysqli_real_escape_string($connection, $old_subject)
$query = "INSERT INTO table (to_email_id,subject) values('$to','$subject');";

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