I'm struggeling with a tiny script which is responsible for 2 things:
- truncating database
- uploading files into database
Looks like that:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$mysql_host = 'localhost';
$mysql_username = 'x';
$mysql_password = 'y';
$mysql_database = 'z';
$db = new PDO('mysql:dbname='.$mysql_database.';host='.$mysql_host,$mysql_username,$mysql_password);
// works not with the following set to 0. You can comment this line as 1 is default
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);
function truncate_db()
{
global $db;
$sql_query_1 = "
TRUNCATE TABLE `VISITS`;
TRUNCATE TABLE `ANIMALS`;
TRUNCATE TABLE `DOCTORS`;
TRUNCATE TABLE `PAYMENTS`;
TRUNCATE TABLE `CUSTOMER`
";
try {
$stmt = $db->prepare($sql_query_1);
$stmt->execute();
echo "Truncate action - OK";
}
catch (PDOException $e)
{
echo $e->getMessage();
die();
}
}
function import_db()
{
global $db;
try
{
$sql_query_2 = implode(array_map(function ($v) {
return file_get_contents($v);
}, glob(__DIR__ . "/*.sql")));
$qr = $db->exec($sql_query_2);
echo "Import action - OK";
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
}
truncate_db();
echo '<br />';
import_db();
$db = null;
?>
Issue - files (sql one) which I'm uploading to the database contains special charaters (like ś, ó, ę etc.) After that I have an issue in the database that some of the words doesn't contain any more those symbols. After upload I have symbols like: ³, ¿ etc. How can I edit function import_db() to keep those characters? i thought about:
mb_convert_encoding
but I have no clue how to incorporate that into my code ;/ in my DB table, column with that words (containing special characters) is set to: UTF8_General_CI. thanks!
I'm unclear on what your problem is
Truncated text is when you try to insert Señor, but find that only Se shows up in the table. This form of truncation is usually caused by
The client had accented characters encoded in latin1 (or latin2, etc), and
SET NAMES utf8 was in effect during the INSERT (or LOAD DATA)
That is, you should either get the text in utf8 or you should change what you tell MySQL the encoding is.
If you can get the hex of the file contents, ś ó ę should be 2-byte hex C59B C3B3 C499 in utf8. latin1 only has ó as a single byte F3. In latin2, those are B6 F3 EA, so perhaps that is where you are coming from?
It is OK to have a mismatch between what SET NAMES says and what CHARACTER SET you have established to table/column. MySQL will convert the encoding as they are transferred.
Do not use mb_convert_encoding or any other conversion functions when using MySQL, it only adds to the confusion.
Also, do the TRUNCATEs one at a time. The API does not like multiple statements.
Related
I have a html form that stores data to mysql. When special characters are used (øæå), it store the characters correcly in the database.
When i use a script to save the mysql table to an CSV file, the CSV file wont show special characters correct anymore.
Any ideas?
$conn = mysqli_connect($hostname, $user, $password, $database, $port);
if (mysqli_connect_errno()) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$csv_export = '';
$query = mysqli_query($conn, "SELECT * FROM ".$db_record);
$field = mysqli_field_count($conn);
for($i = 0; $i < $field; $i++) {
$csv_export.= mysqli_fetch_field_direct($query, $i)->name.';';
}
$csv_export.= '
';
while($row = mysqli_fetch_array($query)) {
for($i = 0; $i < $field; $i++) {
$csv_export.= '"'.$row[mysqli_fetch_field_direct($query, $i)->name].'";';
}
$csv_export.= '
';
}
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=".$csv_filename."");
echo($csv_export);
I assume your script to save the mysql to CSV is run in linux shell or windows command prompt. Problem could be that data stored to database uses different character-set than environment that your script uses.
Check in which format data is stored to database or change it to UTF-8:
ALTER TABLE tbl_name CONVERT TO CHARACTER SET utf8;
And make sure your script environment uses the same character-set. On Ubuntu linux putting following lines to the file /etc/environment might do the trick (da_DK is for Denmark as just a guess from your characters, you need to set it to one your characters use):
LC_ALL=da_DK.UTF-8
LANG=da_DK.UTF-8
Without any symptoms, it is hard to say which of several fixes are necessary. See Trouble with UTF-8 characters; what I see is not what I stored for a list of possible symptoms, together with what causes them.
When loading via LOAD DATA, be sure to specify the character set of the data as part of the statement.
HTML forms should start like <form accept-charset="UTF-8">.
Do not do any ALTERs until you have confirmed that the chosen syntax will be helpful, not make things worse.
The solution to this issue was to declare mysqli_char_set by doing this:
mysqli_set_charset($conn,"utf8");
I am trying to make an article poster that works perfectly until I put special characters in the html form (like ;,! etc.). I Googled it and found something about the table collation (which is utf8_unicode_ci by default).
I have <meta charset="utf-8"> into the header file and mysqli_set_charset($conn, 'utf8') after connection to the database. Also the form has accept-charset="utf-8" attribute.
Here is what happens after sending the form:
if(isset($_POST['sendForm']))
{
$articleTitle = $_POST['title'];
$articleText = $_POST['text'];
$name = $_SESSION['name'];
$currentDateMySQL = date("Y.m.d");
$sql = "INSERT INTO articles (title, text, owner, date_added) VALUES ('$articleTitle', '$articleText', '$name', '$currentDateMySQL')";
$result = mysqli_query($conn, $sql);
if($result === false)
{
$color = "red";
$infoText = "Could not insert your information into the database. Error number: <b>" . mysqli_errno($conn) . "</b>. :( Try again.";
}
else
{
$color = "green";
$infoText = "Succesfully writen the article into the database. :)";
}
}
Also the given error number is 1064. There is no error in the SQL code, it works perfectly without special characters.
You need do escape every input you trying to insert into a database otherwise you risking sql-injection attacks:
$articleText = mysql_real_escape_string($articleText);
Also you shouldn't use native sql directly anymore, it is deprecated. You should use prepared statements instead.
If you changed your table collation after creation, it does not mean your column collation does match.
All of the following charsets should match so that your data is inserted correctly:
column charset collation
connection charset
Even better, to have the same charset everywhere:
defaut charset
database charset
table charset
column charset
connection charset
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".
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)
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.