Inserting latin chars in mysql using php? - php

I have a database that contains latin chars like á, é, ç etc. I can insert tuples with those chars using the MySQL admin interface by writing the SQL insert statements there. I can also read and display them without any problem. But I can't insert new data properly using PHP.
$mysqli = new mysqli("localhost", "root", "", "budgets");
$data = mysqli_real_escape_string($mysqli, "bananá");
$stmt = $mysqli->prepare("INSERT INTO items(id_budget, description, unit_price, quantity) VALUES (1, ?, 3, 3);");
$stmt->bind_param("s", $data);
$stmt->execute();
I have read several threads suggesting to use mysqli_real_escape_string(), and making sure the charsets were configured properly, but nothing worked.
I tried using different charsets in the database but the á is always replaced by strange symbols. Currently I'm using utf8_general_ci as the charset of the database.
Thank you in advance for any assistance.

First thing setup your table rows collcation to utf8_unicode_c
And add $mysqli->set_charset("utf8"); to your connection code
Finaly your code should look like this :
$mysqli = mysqli_connect(HOST_NAME,DB_USER,DB_PASS,DB_NAME);
if($mysqli === false) {
die("Something was wrong ! Please try again later."); // Error if connection not ok.
}
$mysqli->set_charset("utf8");
$data = "bananá";
$stmt = $mysqli->prepare("INSERT INTO items(id_budget, description, unit_price, quantity) VALUES (1, ?, 3, 3);");
$stmt->bind_param("s", $data);
$stmt->execute();
$stmt->close();
$mysqli->close();

Related

MySQL prepared statements can't insert UTF-8 letters [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 6 years ago.
I can get UTF-8 letters from database for example these: ąčęėįšųūž, but can't insert them to database, for some reason only š gets inserted into database, the rest are inserted as ?. I'm connecting to my database through this file:
<?php
$GLOBALS['mysqli'] = new mysqli("...", "...", "...", "...");
$stmt = $GLOBALS['mysqli'] -> prepare("SET NAMES 'utf8'");
$stmt->execute();
?>
And then inserting data through this code:
$linkName = $_POST['linkName'];
$stmt = $GLOBALS['mysqli'] -> prepare
("
INSERT INTO NavigationLinks (linkName, fileName, iconExt)
VALUES (?, ?, ?)
");
$stmt->bind_param("sss", $linkName, $fileName, $iconExt);
$stmt->execute();
$stmt->close();
Before insertion I've tried to echo $linkName and it outputs correct characters.
Use a UTF8 encoding/collation on the tables and columns you want to add UTF8 data to.

mysql cyrillic troubleshooting

Hi guys!
So, I have one question: I have some data which is cyrillic. Here is the problem:
Incorrect string value: '\xD0\xBD\xD0\xBE\xD0\xB2...' for column 'title' at row 1.
Here is my code:
$link = mysql_connect('localhost', 'root', 'pass');
if($link&&isset($_POST['addSticker'])){
$title = $_POST['title'];
$description = $_POST['description'];
$photo = mysql_real_escape_string(urlencode($_POST['photo']));
$quantity = $_POST['quantity'];
$price = $_POST['price'];
mysql_select_db('db_name');
$sql = "INSERT INTO table (title, description, photo, quantity, price) VALUES ('$title', '$description', '$photo', '$quantity', '$price');";
mysql_query("SET NAMES utf8", $link);
mysql_query($sql, $link) or die(mysql_error());
}
Thanks for any help.
First thing is that your query is vulnarable to SQL injections. It is recommended to escape your characters (MySQLi). This might even solve your problem. The second thing is you're still using mysql API which is deprecated. Instead, you should switch to PDO or mysqli API. In case you have bad collation (escaping input doesn't help), you can also change MySQL collation to one of these so that database can understand these characters.

Foreign Characters Such As ü Don't Make It To Mysql

All foreign characters such as umlauts (ü) get deleted when trying to put them into mysql.
In debugging this problem I've went over the following:
My database is UTF-8
The table in question is InnoDB utf8_general_ci. Row is longtext utf8_general_ci
I've added mysqli_set_charset($mysqli, "utf8"); right after $mysqli = new mysqli($hostname, $username, $password, $database);
It goes in using the following php:
$stmt = $mysqli->prepare("
UPDATE post
SET post = ?,
title = ?
WHERE id = ?
");
$stmt->bind_param("ssi", $clean_html, $titlePost, $id);
String before going being updated in db is
<p>SOME NEW TEXT</p><p> </p><p>üü</p>
But still nothing. The umlauts disappear. In the DB it shows up as
<p>SOME NEW TEXT</p><p></p><p></p>
What other debugging steps should I take? Thank you
Try utf8_encode() and utf8_decode() maybe it can help. before setting the value to database try
$value = utf8_encode($value);

How to upgrade from mysql_* to mysqli_*?

I'm currently using deprecated code to get data from users, as follows:
/* retrieve */
$lastName = $_POST['lastName'];
$firstName = $_POST['firstName'];
$examLevel=$_POST['level'];
/* connect */
$dbc=mysql_connect("localhost", "user", "passw") or die('Error connecting to MySQL server');
mysql_select_db("db") or die('Error selecting database.');
/* sanitize */
$lastName=mysql_real_escape_string($lastName);
$firstName=mysql_real_escape_string($firstName);
$examLevel=mysql_real_escape_string($examLevel);
/* insert */
$query_personal = "INSERT INTO personal (LastName, FirstName) VALUES ('$lastName', '$firstName')";
$query_exam = "INSERT INTO exam (Level, Centre, BackupCentre, etc.) VALUES ('$examLevel', '$centre', '$backup', 'etc')";
This is working but I keep coming across warnings about security and lack of support. There's a small rewrite to connect with mysqli instead of mysql but what about mysqli_real_escape_string? I've seen it used in examples but I've also seen advice to use prepared statements instead which don't use mysqli_real_escape_string.
And how would I use prepared statements to INSERT my data? I'm a bit at sea with this bit so far. For example, is parameter binding only for INSERTs and result binding only for SELECTs?
Convert it to PDO
/* connect */
$dsn = "mysql:host=localhost;db=test;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,"user", "passw", $opt);
/* insert */
$query = "INSERT INTO personal (LastName, FirstName) VALUES (?, ?)";
$stmt = $pdo->prepare($query);
$stmt->execute(array($_POST['lastName'],$_POST['firstName']));
$query = "INSERT INTO exam (Level, Centre, BackupCentre, etc) VALUES (?, ?, ?, 'etc')";
$stmt = $pdo->prepare($query);
$stmt->execute(array($_POST['level'], $centre, $backup));
see this pages for converting mysql into mysqli
Converting_to_MySQLi
https://wikis.oracle.com/display/mysql/Converting+to+MySQLi
and see mysqli_real_escape_string manual that explain about mysqli_real_escape_string and Security problem and how to solve it.
php.net:
Security: the default character set
The character set must be set either at the server level, or with the API function mysqli_set_charset() for it to affect mysqli_real_escape_string(). See the concepts section on character sets for more information.
see this page for query for insert data
see this page for prepare data for inserting to mysql
and http://php.net/manual/de/mysqli.quickstart.prepared-statements.php

How can I get PDO bindValue/bindParam to bind with MySQL?

I've been using mysql and mysqli in the past, but am starting a new project, so wanted to go back to OOP with PDO-mysql .. however, it doesn't want to work:
$dbh = new PDO('mysql:host='.$host.';dbname='.$database, $username, $password);
if(isset($_POST["name"]) && isset($_POST["password"]))
{
$pwdHasher = new PasswordHash(8, FALSE);
$hash = $pwdHasher->HashPassword($_POST["password"]);
//$insert = $dbh->prepare('insert into users (username,password) values ("?","?")');
$insert = $pdo->prepare("insert into users (username,password) values (?,?)");
$insert->bindParam(1,$_POST["name"]);
$insert->bindParam(2,$hash);
$insert->execute();
echo "Registration Success!";
}
edit: The above code works if I change the code from the commented line to the non-commented (i.e. single quote to double quotes) However, this doesn't work later:
$query = $pdo->prepare("select * from users where username = ?");
$query->bindParam(1,$_POST["name"]);
$result = $query->execute()
Ok, you've found the answer to your first question.
For the second one it would be
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
called right after connect.
it will tell you what's going wrong with your query.
error_reporting(E_ALL);
also always helps with such errors like misspelled variables ($pdo is not $dbh for example)
If you want to use ? for placeholders, you are supposed to send an array to the execute-method matching the positions of the question marks. $insert->execute(array('value1', 'value2'));
You could however use named placeholders .. WHERE x = :myxvalue and use $insert->bindValue(':myxvalue', 'thevalue', PDO::PARAM_STR);
Also, please have a look at the difference between bindParam and bindValue
The answer to this question is simple and embarrassing:
I need to change the single quotes surrounding the sql statement being prepared to double quotes (and remove the double quotes where the '?' mark is.
change:
$insert = $dbh->prepare('insert into users (username,password) values ("?","?")');
to
$insert = $dbh->prepare("insert into users (username,password) values (?,?)");
and everything works.

Categories