user2104806
user2104806

Reputation: 95

Inserting latin chars in mysql using 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.

Upvotes: 0

Views: 365

Answers (1)

Mourad Karoudi
Mourad Karoudi

Reputation: 378

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

Upvotes: 1

Related Questions