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();
Related
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.
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)."'";
I am having issues inserting double quotes into my mysql database.
I had to change headers to UTF8 since I will be displaying Spanish (ñ, accents).
I run a page (PHP) to insert a message in my database:
header('Content-Type: text/html; charset=utf-8');
$newMessage = $_POST['newChatMessage'];
$currentUser = $_SESSION['mundialUser'];
$currentUserId = $_SESSION['idPlayer'];
$newMessage = $_POST['newChatMessage'];
date_default_timezone_set('America/New_York');
$messageDate = date( "Y-m-d H:i:s", time());
$chatMessageQuery = "INSERT INTO chat (message, user, user_id, date) values (:message, :user, :user_id, :date)";
$con->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
$chatMessage = $con->prepare($chatMessageQuery);
$chatMessage->execute(array(':message'=>$newMessage, ':user'=>$currentUser, ':user_id'=>$currentUserId, ':date'=>$messageDate));
When I check in the database, double quotes come up like \" instead of simply ". The Spanish ñ is inserted like this: ñ.
Then to display, my main page has this in the Head:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
And I print the message retrieved from the database using utf8_decode.
The outcome is: the Spanish ñ shows correctly but the double quotes are displayed like \" and not "
What am I missing when inserting into my db or displaying?
double quotes come up like \" instead of simply "
Some of your code is adding these slashes. Or ancient feature of magic quotes is turned off. Either should be disabled.
The Spanish ñ is inserted like this: ñ.
It makes very little sense sending mysql init command when the actual init has been done already.
SET NAMES is not a magic chant that require some special dance to perform, but rather plain and simple SQL query. So, you can run it via query() method. Or, better, set charset in DSN.
You should look the charset of you tables/database. At least in Portuguese it can be a headache
i have a very strange phenomena trying to migrate an older php project from iso-8859-1 to utf-8
when typing a german umlaut like "äöüß" into a textfield an submitting it i receive broken ones like "äöüÃ�"
header is set to
<?php header("Content-Type:text/html;charset=UTF-8"); ?>
<meta charset="UTF-8" />
the form is set to
<form accept-charset="utf-8">
and so on - i tried everything i could think of - anybody got an ide or experience with an alike problem?
best regards,
Lupo
i found a solution thats working for my case:
i had to change the accept-charset from UTF-8 back to ISO-8859-15 then the field values look ok again - to be able to process the received data i have to utf8_encode them - seems a bit weird but it works fine now.
Thank you all for your time and Jukka for the help.
best regards,
Lupo
I'm glad you managed to find a solution.
And if you don't want to worry about so many different charset codings or if htmlentities doesn't work for others, 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.
$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
//Optinal:
$charset = mysqli_character_set_name($link); //only works for mysqli DB connection
printf ("To check your character set but not necessary %s\n",$charset);
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