Escaping Special character - php

I am inserting data in mysql table , prior to that i am escape sequencing variable
$data = mysqli_real_escape_string($con,$data);
Every thing is working fine , but when i am getting data like this
$data = " SHR′ n(X′) ";
its escaping data like this
SHR′ n(X′)
which is not inserting in database and giveing error, So my question is how can i make it to escape this kind of characters.
Note:I have created a table with utf8_general_ci as collation.
Thanks

Try this
after establish connection use
mysqli_set_charset ($con, "utf8");

Try to set the charset to utf8.
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
} else {
printf("Current character set: %s\n", $mysqli->character_set_name());
}

Related

Query special characters from mysql db

I am using PHP 7.1.8 and I am trying to query my db. However, the serialized arrays have special characters, which are shown as the following: �
Find below an example of my code:
// connect to db
$dbname = $conf['dbName'];
$dbuser = $conf['user'];
$dbpass = $conf['pwd'];
$dbhost = $conf['host'];
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$arr = $conn->query("SELECT * FROM postmeta WHERE post_id = "100" and meta_key = 'val' LIMIT 1;")->fetch_assoc()["meta_value"];
When querying the database directly, I get the correct value for �. See below my ``$arr`:
This error results basically in that I cannot unserialize the data correctly.
Any suggestions how to fix this error?
I appreciate your replies!
The problem lies in collation. Your MySQL returns specific symbols (temperature symbol) that is not supported by your current encoding.
Try to execute this query right before your selects:
set names 'utf8';
Also, if you're showing this data in some kind HTML response, don't forget to add charset=UTF-8 to your meta tag of Content-type.
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
/* change character set to utf8 */
if (!$conn->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $conn->error);
exit();
} else {
printf("Current character set: %s\n", $conn->character_set_name());
}
$arr = $conn->query("SELECT * FROM postmeta WHERE post_id = "100" and meta_key = 'val' LIMIT 1;")->fetch_assoc()["meta_value"];
Please check the output.

Wrong character encoding

I have two forms on two different pages which are used to insert data to an MySQL database. I have some special character like 'čšžćđ' in my form data which I pass via the forms to the insertion scripts.
The data from the first form gets inserted correctly, while some fields from the second form contain the '?' characters, which would indicate a mismatch in encoding.
The two insertion scripts of both the forms are using the same file to connect to the database and set the encoding, like below:
<?php
$username = "root";
$password = "";
$servername = "localhost";
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($conn, "testdb");
if (!$conn) { // check if connected
die("Connection failed: " . mysqli_connect_error());
exit();
}else{
/* change character set to utf8 */
if (!mysqli_set_charset($conn, "utf8")) {
// printf("Error loading character set utf8: %s\n", mysqli_error($conn));
} else {
// printf("Current character set: %s\n", mysqli_character_set_name($conn));
}
mysqli_select_db($conn, "testdb");
//echo "Connected successfully.";
// Check if the correct db is selected
if ($result = mysqli_query($conn, "SELECT DATABASE()")) {
$row = mysqli_fetch_row($result);
//printf("\nDefault database is %s.\n", $row[0]);
mysqli_free_result($result);
}
}
?>
I guess this would mean, that the client character encoding isn't set correctly? All database tables have the utf_8 encoding set.
Try to set encoding on top of the page
<?php
header('Content-Type: text/html; charset=utf-8');
other code...
Are you talking about HTML forms? If so,
<form accept-charset="UTF-8">
Is it one ? per accented character? When trying to use utf8/utf8mb4, if you see Question Marks (regular ones, not black diamonds),
The bytes to be stored are not encoded as utf8. Fix this.
The column in the database is CHARACTER SET utf8 (or utf8mb4). Fix this.
Also, check that the connection during reading is utf8.
The data was probably converted to ?, hence cannot be recovered from the text.
SELECT col, HEX(col) FROM ... to see what got stored.
? is 3F in hex.
Accented European letters will have two hex bytes per character. That includes each of čšžćđ.
Chinese, Japanese, and Korean will (mostly) have three hex bytes per character.
Four hex characters would indicate "double encoding".

Store and output text with accents

I have some text in a database. I use French and English. French has accents, and some special characters like ç. I use Mamp, MySQL and PHP.
I have collation latin1_swedish-ci (the default). I tried utf8_general_ci and the result is the same.
If I use in a html page, I have this in the head: <meta charset="UTF-8">
As an example, in the database I have "voilà".
When I echo the text from the database to html:
$con = mysqli_connect("localhost","root","root");
if (!$con) {
die('The connexion failed: ' . mysqli_error());
}
if (!mysqli_select_db($con, 'prova')){
echo "Connection with database was not possible";
}
$result = mysqli_query($con, "SELECT * FROM test1
WHERE id='1' ")
or die(mysqli_error());
while($row = mysqli_fetch_array($result)) {
$text = $row['first'];
echo $text; //I see: voil�
echo htmlentities($text); //I see nothing
echo utf8_encode($text); //This works: I see voilà
}
Why htmlentities does not work?
Is utf8_encode(); the way to go? I have to use that always when I output something from the database? Why do I have to use that if the collation is already UTF8? Is there any better way to store and output text with accents in a MySQL database?
After you connect to the DB you should set the client charset to UTF8:
mysqli_set_charset($con, "UTF8");
Otherwise the mysql client transforms the UTF8 'voilà' to latin1 ('cause it seems that is it's default).
Either you tell the client that I want everything in UTF8, or you get it with the default latin1, and convert it one-by-one yourself calling utf8_encose($text)

Php mysql returning?

I have a problem, when I try to echo a cyrillic character, it return like ????
Here's code
<?
include('db.php');
$sql = "SELECT * FROM menu_items WHERE reference=1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$rows = array();
while($row = $result->fetch_object()) {
$rows[] = json_encode($row);
}
$items = implode(',',$rows);
echo '['.$items.']';
}else {
echo "ERROR";
}
?>
Any idea?
Collation : utf8_general_ci
And db.php:
<?
$servername = "localhost";
$username = "test";
$password = "Conqwe333!";
$conn=mysqli_connect($servername,$username,$password,"test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Worked after <? $conn->set_charset("utf8");?>
Add before your $sql
$conn->query('SET NAMES utf8');
You can read more about it here
Also you will need to set proper header for browser. You can do it by serveral ways for example in meta html tag or using header('Content-Type: text/html; charset=utf-8');
You should set collation per connection:
mysqli_set_charset
Also you can perform sql
SET NAMES utf8;
but it's not recommended
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
} else {
printf("Current character set: %s\n", $mysqli->character_set_name());
}
$mysqli->close();
I am assuming you are using Bulgarian and UTF8, same will work for Russian and other languages, just change "bg" to proper string.
I do not recommend you to use cp1251, because it breaks unexpectedly with apache mod_rewrite and other tools like this.
You need to do following checks:
Check if your database / table collation is some UTF8. It could be utf8_general_ci or Bulgarian - difference is minimal and is more sorting related. (utf8_general_ci is perfectly OK)
Check you have following statement executed right after connect - set names UTF8;. You can do $mysqli->query("set names utf8");
Make sure you have proper "tags". Here an example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang='bg' xml:lang='bg' xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Нов сайт :)</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
You can include UTF8 "BOM" on the html, but it works pretty well without it. I usually work without "BOM", and when I want to be 100% complaint, I create an include file bom.php that contain just the BOM symbol and include it prior HTML template in normal PHP way, e.g. include "bom.php".
Hope this helps, if not, please comment.
EDIT:
Someone suggested you must be sure if your data is properly stored in MySQL. Easiest way is to open PHP MySQL Admin. If Cyrillic is shown there, all is OK.
I think the issue is a step back, try to first encode the cyrillic characters correctly: How to encode cyrillic in mysql?

Query fail with no error

I have a database UTF8 encoded, because it contains arabic letters. I have a php file to select all values from a given table:
<?php header('Content-type: application/json; charset=utf-8');
$host = "localhost"; //Your database host server
$db = "kalimat"; //Your database name
$user = "root"; //Your database user
$pass = ""; //Your password
$connection = mysqli_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
die(mysqli_error($db));
}
else
{
//Attempt to select the database
$dbconnect = mysqli_select_db($connection, $db);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$auteur=utf8_decode(urldecode($_GET["artist"]));
//$auteur=utf8_decode($auteur);
$resultset = mysqli_query($connection,"SELECT * FROM $auteur");
if( $resultset )
{
$records = array();
//Loop through all our records and add them to our array
while($r = mysqli_fetch_assoc($resultset))
{
$records[] = $r;
}
$records = array_map(function($r) {
$r['artist'] = utf8_encode($r['artist']);
return $r;
}, $records);
//Output the data as JSON
echo json_encode($records);
}
else{
die("Error:".mysqli_error()); //Here is the error
}
}
}
?>
In output, I have "Error:" without any specification, so I can't know the source of the problem.
Any something strange in the php file?
Thank you for your help.
have you tried utf8mb4 ?
ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
utf8mb4 is superset of utf8
Advice: database ,table names and columns you should make them in non utf8 characters.
EDIT:
to handle with utf8 characters you have to make all in utf8 such as:
your files , convert them to utf8 , all pages where you are using utf8 also that page where you geting the author fom.
database , tables , columns.
your editor where you write codes.
headers.
...
try putting the following lines just after the php tag starts and error will be displayed.
error_reporting(E_ERROR);
ini_set("display_errors",1);
hope this helps.
You are using mysqli, not mysql. So you have to use appropriate error function, and call it according to it's proper syntax.
Also, your idea on storing data in user-defined tables is wrong. You have to learn relational database basics first.

Categories