Apostrophe does not work in mysql/PHP [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
apostrophes are breaking my mysql query in PHP
My Android App is sending a message to my server (PHP script)
The PHP script is writing the message into MySQL.
It works fine, but all messages containing an apostrophe ' (e.g. he's going to school) are not written into the database.
Here the php script:
function deq($s)
{
if($s == null)
return null;
return
get_magic_quotes_gpc() ?
stripslashes($s) : $s;
}
if(md5(deq($_REQUEST['blub']).deq($_REQUEST['blub'])."blabla") == $_REQUEST['hash']){
mysql_connect("localhost", "blub", "blub") or die(mysql_error());
mysql_select_db("blub") or die(mysql_error());
// mysql_set_charset('UTF8'); // does not work as too old php
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET COLLATION_CONNECTION = 'utf8_unicode_ci'");
$mysqldate = gmdate( 'Y-m-d H:i:s');
$language = (int) $_REQUEST['language'];
$device = $_REQUEST['device'];
$ipaddress = $_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO test(username, text, language, rating, checked, date)
VALUES('".$_REQUEST['username']."', '".$_REQUEST['text']."', '".$language."', '0' , 'false', '".$mysqldate."') ")
or die(mysql_error());
mysql_close();

All you need to escape ' like below
$_REQUEST['text'] = mysql_real_escape_string($_REQUEST['text']);

Don't use magic quotes.
use mysqli_real_escape_string or mysql_real_escape_string if you don't want to use mysqli.

You have discovered SQL injections: The apostrophe in the input "gets out" of the apostrophe you put in the query. This causes some of the input to be considered part of the query. You can use mysql_real_escape_string to secure the input before you use it in a query. But in general, there are better solutions for this (e.g. prepared statements).
You are, by the way, using the outdated mysql_ functions in PHP (see the big red warning on http://php.net/mysql_query)

Looking at the description above you need to escape input data with slashes using mysql_real_escape_string function
Apostrophe in input data when utilized in sql query will break the sql query resulting into sql injection
So always sanitize input data with mysql_real_escape_string() function before utilizing into sql query
For more documentation about mysql_real_escape_string() function please refer the documentation mentioned in below url
http://php.net/manual/en/function.mysql-real-escape-string.php

Related

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.

empty result from mysql with “\” and “-” in query

i have SQL query :
SELECT count(art),art,art_manufacturer,group_manufacturer
FROM goods
WHERE art_manufacturer = 'ГКБ-44/150'
when i using phpMyAdmin, result of query is:
1, 950000258, ГКБ-44/150, Интерскол
my php file contain:
$art="ГКБ-44/150";\\debug
$query = "SELECT art,art_manufacturer,group_manufacturer FROM goods WHERE art_manufacturer = '".$art."'";
$sql = mysql_query($query);
while ($recResult = mysql_fetch_array($sql))
{ \*do somting*\ }
where is my mistake? why the result of query in php is empty?
my solution
i had mysql_query("SET NAMES cp1251"); in my code
when i start use mysqli i commented mysql_query("SET NAMES cp1251");
mistakenly i thought mysqli is solution, after i discommented mysql_query("SET NAMES cp1251"); i got problem again.
So what's happend?
my PHP file in UTF-8 and when i use mysql_query("SET NAMES cp1251"); i had SELECT art,art_manufacturer,group_manufacturer FROM goods WHERE art_manufacturer = "ГКБ-44/150"; query to mysql DB
It's empty because these are specially reserved characters interpreted by PHP/SQL. I would suggest you take a look at parameterised queries or PDO, they will escape strings for you as part of their function.
EDIT: Also it could be that the encoding of your server doesn't accept Unicode characters. I would ensure your site is using UTF-8.
You should stop using mysql_* functions they are deprecated for a long time.
Use mysqli or PDO and bind parameters to the query not concatenate the query string with some not prepared php variables.
So just to help you pass over the issue this time you can:
$query = "SELECT art,art_manufacturer,group_manufacturer
FROM goods
WHERE art_manufacturer = '".mysql_real_escape_string($art)."'";

How to store the apostrophe into MySQL database from user input? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 9 years ago.
I have a simple comments page a user enter a text into a textarea and the hit comment button to send the comment to a php page :
<?php
$reply = strip_tags($_POST['reply']);
$comment_id = strip_tags($_POST['id']);
$id = strip_tags($_POST['user_id']);
$date = strip_tags($_POST['date']);
$time = strip_tags($_POST['time']);
$server_root = "./";
if(file_exists("{$server_root}include-sql/mysql.class.php"))
{
include_once("{$server_root}include-sql/mysql.class.php");
}
include_once("{$server_root}config.php");
$db1;
$db1 = new db_mysql($conf['db_hostname'],
$conf['db_username'],
$conf['db_password'],
$conf['db_name']);
$db1->query("SET NAMES utf8");
$current_server_date = date('Y-m-d H:i:s');// Your local server time
date_default_timezone_set('Asia/Istanbul');
$current_pc_date = date('Y-m-d H:i:s');
$sql = $db1->query(
'INSERT INTO replies1 (reply, comment_id, date, time, timestamp, user_id)
VALUES ("$reply", $comment_id, "$date", "$time", "$current_pc_date", $id)');
?>
the problem is : when a user enter any comment with apostrophe it does not store it in the database ? why does that happened? Is my code has something wrong? I added everything the double quotes and stripe_tags.? did i miss something?
You should escape all input which is coming directly from the user with mysqli_real_escape_string()!
Otherwise its not only not working properly but its also highly unsafe to hacker-attacks. (mysql-injection)
The strip_tags() seems unnecessary.
Instead, you should
either escape the DB input appropriately
or use prepared statements at the first place.
As you hide your MySQL implementation in an own class, I don't see how you implement these. How to escape or to prepare depends on the MySQL interface you use.
Keep in mind that mysql_*() is deprecated. You should either use mysqli or PDO.

MySQL Insert special characters

I had a registration form which will insert into a member table, the collation is in utf8_general_ci, and I use SET NAMES utf8 in php script, OK here is the problem, I can't insert a string other than pure alphabet, I try input 'Hélène' in a form field, after the sql query run, I check with my db table, the field is inserted as 'H', the rest of the alphabet cannot be insert whenever the string come with special alphabet such as é, ř on behind.
Can someone please help? thanks.
SOLUTION:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
mysql_query("SET NAMES utf8");
above two line is crucial part to accept input into database and output on a webpage.
Thanks everyone for the advise.
try to insert data after encoding. try mysql_real_escape_string() to encode. then execute insert query.
EDIT:-
This answer was posted one year ago. Now mysql_real_escape_string() for php 5 will work in mysqli::real_escape_string this format. please check here
And if you don't want to worry about so many different charset codings or if htmlentities doesn't work for you, here the alternative:
I used mysqli DB connection (and PHPV5) Form post for writing/inserting to MySQl DB.
$Notes = $_POST['Notes']; //can be text input or textarea.
$charset = mysqli_character_set_name($link); //only works for mysqli DB connection
printf ("To check your character set but not necessary %s\n",$charset);
$Notes = str_replace('"', '"', $Notes); //double quotes for mailto: emails.
$von = array("ä","ö","ü","ß","Ä","Ö","Ü"," ","é"); //to correct double whitepaces as well
$zu = array("ä","ö","ü","ß","Ä","Ö","Ü"," ","é");
$Notes = str_replace($von, $zu, $Notes);
echo " Notes:".$Notes."<br>" ;
$Notes = mysqli_real_escape_string($link, $Notes); //for recommended mysqli DB connection.
//$Notes = mysql_real_escape_string($Notes); //for old deprecated mysql DB connection.
// mysqli_real_escape_string Escapes special characters in a string for use in an SQL statement
echo " Notes:".$Notes ; //ready for inserting
The reason you are not able to do so is because PHP prevents a set of special characters to be sent to database to avoid things like sql injection. You can use the escape string function if you wish to escape but the best way to do so is by using the prepared statements.
$connection = <"Your database connection">;
$userinput = "Special characters Hélène";
$stmt = $con->prepare("insert into `table` (`fieldname`)values(?)");
$stmt->bind_param("s",$input);
$stmt->execute();

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