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

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);
}

Related

Proper quotation in mysqli_query

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

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.

mysqli_query inputs via variable

I'm trying to add information to a MySQL table using the following PHP code. (The input the name and text from an HTML5 basic web form.) Probably a syntax issue?
<?php
include "dbinfo.php"; //contains mysqli_connect information (the $mysqli variable)
//inputs
$name = $_GET["name"];
$text = $_GET["text"];
$sqlqr = 'INSERT INTO `ncool`.`coolbits_table` (`name`, `text`, `date`) VALUES ("$name", "$text", CURRENT_TIMESTAMP);'; //the query. I'm pretty sure that the problem is a syntax one, and is here somewhere.
mysqli_query($mysqli,$sqlqr); //function where the magic happens.
?>
No error is thrown. A blank screen results, and a row with "$name" and "$text" is added to the MySQL table.
First of all: you should use mysqli prepared statements to prevent SQL injection attacks. It is not safe to use user input within a query without proper escaping. Prepared statements are useful to prevent this.
Second: you should learn how string quoting works in PHP, single quoted strings and double quoted strings are different
I would recommend to read the PHP documentation about string quoting.
This is how your code should look (with added SQL Injection protection):
<?php
include "dbinfo.php"; //contains mysqli_connect information (the $mysqli variable)
//inputs
$name = mysqli_real_escape_string($_GET['name']);
$text = mysqli_real_escape_string($_GET['text']);
$sqlqr = "INSERT INTO `ncool`.`coolbits_table` (`name`, `text`, `date`) VALUES ('" . $name . "', '" . $text . "', CURRENT_TIMESTAMP);";
mysqli_query($mysqli,$sqlqr); //function where the magic happens.
?>
Take a look at what I've done. Firstly I've escaped the user input you're retrieving into the $name and $text variables (this is pretty much a must for security reasons) and as others have suggested you should preferably be using prepared statements.
The problem is that you weren't surrounding string values with single quotes ('), which is a requirement of the SQL syntax.
I hope this helps to answer your question.

PHP MySQL INSERT statement syntax error

I'm having problems with an INSERT statement, and the error only says:
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 '' at line 1
It's not helpful at all.
The version I have tried so far and failed is:
mysql_query("INSET INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')");
[needless to say that the two variables when printed show the right values]
I've also tried versions with nothing around the table name, with ` or ', a million combinations really and nothing works. Not even with constants or into different tables. It just won't insert anything ever. I've checked the privileges (I'm logging into it with root), and it's all on.
I've tried similar stuff on two different machines with the same server (XAMPP 1.7.7) and it works. I'm completely baffled! What can it be?
Thank you for your time!
First and foremost, just type INSERT correctly.
Using _GET like that really opens you up to SQL INJECTIONS...
Do take a look into MySQL prepared statements.
It is also considered good practice to name the columns that you're inserting data into. That allows you to, latter on, insert extra-columns and keep application logic.
INSERT INTO cos(rowName1, rowName2) VALUES(?, ?)
Where ? would be prepared statements.
Correct:
mysql_query("INSERT INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')");
Have you tried passing the $link to mysql_query ?
Like:
mysql_query("INSERT INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')", $link);
EDIT:
And of course you must take some security measures before inserting anything into the database, maybe mysql_real_escape_string() or even prepared statements.
You are doing it wrong. Why aren't you escaping the values?
Php.net documentation is providing some good and safe working examples:
$query = sprintf("SELECT firstname, lastname, address, age FROM friends
WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
// Perform Query
$result = mysql_query($query);
So adapted to your code:
$query = sprintf("INSERT INTO `cos` VALUES (%s, %s);",
mysql_real_escape_string($_GET['prod']),
mysql_real_escape_string($_GET['page']));
$result = mysql_query($query);
Please, always escape your values. And use INSERT, not INSET :)
first this is you are using INSET make it correct with INSERT like
$pro = mysql_real_escape_string($_GET['prod']);
$page = mysql_real_escape_string($_GET['page']);
mysql_query("INSERT INTO `cos` (column1, column2)
VALUES ('$pro', '$page')" );
you forget to set the column names...
Try this:
$prod = $_GET['prod'];
$page = $_GET['page'];
mysql_insert("INSERT INTO 'cos' VALUES('$prod','$page)");
This should very well do it :)

What characters ARE allowed when querying a mysql database?

I have a textarea in a form, when I enter special characters in it, I get an error in mysql. (when submitting the form to a php-file which does the work of inserting into mysql)
I need to know exactly what characters that aren't allowed, or easier would be, exactly what characters thar ARE allowed, so that I could validate the textarea before submitting.
Does anybody know?
I have tried mysql_real_escape_string() but didn't help...
NOTE: In the textarea, users are supposed to enter some special chars like these:
+ , . ; : - _ space & % ! ? = # * ½ # / \ [ ] ' " < > £ $ €
Probably got them all...
how can I do this?
Thanks
UDPATE
My mysql_query :
mysql_query("INSERT INTO cars_db (description) VALUES ('$ad_text')");
UPDATE
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 'a"a!a?aa+a-a_a
a/a\a[a]a}a{a&a%a#a#a¨a^a*a*aa,a.a:a;a|a½a
§a' at line 1
A database column can technically hold any of those characters. The problem is that you are not escaping them properly in your query.
One way way to do this using mysql_real_escape_string is as follows:
$sql=sprintf("insert into cars_db (description) values ('%s')",
mysql_real_escape_string($_POST['description']) );
//execute query and show errors that result...
$result = mysql_query($sql);
if (!$result) {
die("Oops:<br>$sql<br>".mysql_error());
}
Another way is to use a library like PDO or ADODb which makes it easier to use prepared statements with placeholders. Such libraries ensure that data injected into queries is properly escaped.
This is good practice not only because it solves your problem, but it also improves the security of your code, since it becomes harder to perform SQL injection attacks.
Another way would be to use prepared statements. This makes sure SQL injection isn't possible.
Instead of escaping characters so as not to trip up your query, why not create a stored procedure with an incoming String parameter. Just pass the form variable's value (or save it to a string) and pass that to the stored procedure.
Do this:
$ad_text = mysql_real_escape_string($ad_text);
mysql_query("INSERT INTO cars_db (description) VALUES ('$ad_text')");
Read up on mysql_real_escape_string and SQL injection. This is a massive security hole in your application.
http://us.php.net/mysql_real_escape_string

Categories