Skip to content
Advertisement

MySQL foreign characters after inserting data

I’m using php to insert data from inputs into MySQL database. The problem is, it shows up in phpmyadmin as foreign characters. I’ve already set my database to utf8_hungarian_ci as you can see here: https://i.gyazo.com/aeca91e44e8f1808bad09584d8e938d7.png

I’m using utf 8 charset in my form:

<?php
header('Content-type: text/html; charset=utf-8');
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Records Form</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="firstName">Név:</label>
<input type="text" name="name" id="firstName">
</p>
<p>
<label for="lastName">Foglalkozás:</label>
<input type="text" name="job" id="lastName">
</p>
<p>
<label for="emailAddress">Email:</label>
<input type="text" name="email" id="emailAddress">
</p>
<input type="submit" value="Add Records">
</form>
</body>
</html>

and I’m also using mysqli_set_charset in my sql connector:

<?php
$link = mysqli_connect("localhost", "root", "", "reg");

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Escape user inputs for security
$name = mysqli_real_escape_string($link, $_REQUEST['name']);
$job = mysqli_real_escape_string($link, $_REQUEST['job']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);

// attempt insert query execution
$sql = "INSERT INTO cards (name, job, email) VALUES ('$name', '$job', '$email')";
if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

// close connection
mysqli_set_charset($link, "utf8");
mysqli_close($link);
?>

but I still get this result on my page with characters like ő, ú, ű, á, etc. https://gyazo.com/ab3d40574f0c2162aa6b529651e413b3

Edit: I’m also using this header on my index page:

header('Content-type: text/html; charset=utf-8');

Advertisement

Answer

I had to set the charset at the end just before closing the connection.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement