Alternative to manual "SET NAMES utf8" on every database call [duplicate] - php

This question already has answers here:
Whether to use "SET NAMES"
(3 answers)
Closed 9 years ago.
I have Japanese on my site coming from a mysql database.
Other Japanese text on the site displays fine, but the stuff coming out of the database looks like:
????????
The database is set to UTF8, so is the web page.
To fix the issue, before I make any calls to the database I use:
$db->query("SET NAMES utf8");
I was wondering if there was a better/easier way to do the above without having to set names before every query?

You don't have to use SET NAMES utf8 before every query, you just have to run it once the connection is established. Here's an example with PDO :
try {
$dns = "mysql:host={HOST};dbname={DB}";
$user = "{USER}";
$pass = "{PASS}";
$con = new PDO($dns, $user, $pass);
} catch ( Exception $e ) {
echo "Connexion error ", $e->getMessage();
die();
}
$con->query("SET NAMES utf8;");
//and now, as many queries as you want
If you're using PHP >= 5.3.6, you can define the charset in the connection string (prior PHP versions ignore it) :
try {
$dns = "mysql:host={HOST};dbname={DB};charset=utf8";
$user = "{USER}";
$pass = "{PASS}";
$con = new PDO($dns, $user, $pass);
} catch ( Exception $e ) {
echo "Connexion error ", $e->getMessage();
die();
}
//and now, as many queries as you want

Related

Why I'm not able to create a new database in MySQL using PDO? Is it necessary to have a database already present before creating a new one using PDO? [duplicate]

This question already has answers here:
Pdo connection without database name?
(4 answers)
Closed 5 years ago.
I've installed the latest available version of XAMPP Package on my machine running on Windows 10 Home Single Language Edition.
I'm learning PHP and MySQL.
So, first of all in order to create a new database I wrote following code :
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
}
catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();//Getting 'Notice : Undefined variable : sql' for this line
}
$conn = null;
?>
The database didn't get created and I received following error in output after running above file in a web browser :
Notice: Undefined variable: sql in prog_1.php on line 16
SQLSTATE[HY000] [1049] Unknown database 'mydb'
Can someone please help me by correcting my code, so that I can further start studying the database concepts in actual manner?
Is it necessary to have a database already present when accessing the same using PDO?
P.S. : The database titled 'mydb' is currently not present in MySQL RDBMS.
You're setting the DB name in your DSN connection string, and it looks like mydb doesn't exists.
Just remove that part from the DSN string and try again.
Your $conn = new PDO() fails because there isn't a database called myDB (SQLSTATE[HY000] [1049]). Because that line fails your try catch statement will evaluate to the catch part before it declares the $sql variable. So when you try to access the $sql variable in the catch part it does not exist and will throw an Undefined variable error.
You'll have to move the $sql above the $conn = new PDO() line to fix the undefined variable error. To fix the missing database error you'll have to create a database called myDB.
try {
$sql = "CREATE DATABASE myDBPDO"; // moved it here
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// (...)
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage(); // no undefined variable
}
To connect to the database without selecting a specific database you'll have to change your new PDO() DSN to this:
$conn = new PDO("mysql:host=$servername", $username, $password);
For more information please check this answer.

How to insert data which contain non english letter in php slimframwork

I am working with PHP slim framework to develop API. I can GET and DELETE but with the inserting (POST) and updating (PUT), I am facing problems.
class db {
//Propertise
private $dbhost = 'localhost';
private $dbuser = 'root';
private $dbpass = '';
private $dbname = 'bralivnara-api';
//Connect
public function connect(){
try {
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', 'CHARSET utf8');
$dbConnection = new PDO("mysql:host=$this->dbhost;dbname=$this->dbname;", $this->dbuser, $this->dbpass, $options);
// set the PDO error mode to exception
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
return $dbConnection;
}
}
When I use rest easy I receive the 500 error.
Response Status: 500 (Internal Server Error)
When I passed the URL and press enter in browser, it shows the error
Connection failed: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'add' at line 1
Before I had an issue with Swedish letters also, it was not displaying in browser correctly. If anyone has same issue you can fix this issue with that header. It will work for all non-English letters
return $response->withStatus(200)
->withHeader('Content-Type', 'application/json;charset=utf-8;')
->write(json_encode($tranasVcDatainsamling, JSON_UNESCAPED_UNICODE));
If you want to see complete get code you can join our discussion.
Now the last problem which still remains is inserting to database. Here is the code for insertion to the database.
$app->post('/api/tranas-vc/add', function (Request $request, Response $response){
$besöksdatum = $request->getParam('besöksdatum');
$kön = $request->getParam('kön');
$ålder_år = $request->getParam('ålder_år');
$sökorsak = $request->getParam('sökorsak');
$vp_objektiv_prio = $request->getParam('vp_objektiv_prio');
$vp_objektiv_variabel_med_högst_prio = $request->getParam('vp_objektiv_variabel_med_högst_prio');
$vp_mätning_prio = $request->getParam('vp_mätning_prio');
$vp_mätning_variabel_med_högst_prio = $request->getParam('vp_mätning_variabel_med_högst_prio');
$ess_val = $request->getParam('ess_val');
$prio_ess = $request->getParam('prio_ess ');
$prio_total = $request->getParam('prio-total');
$utskrivning_hänvisning_återbesök = $request->getParam('utskrivning_hänvisning_återbesök');
$åtgärd_remiss = $request->getParam('åtgärd_remiss');
$om_lab_vilka_prover = $request->getParam('om-lab-vilka-prover');
$sql = "INSERT INTO
`tranasvcdatainsamling`
(
`besöksdatum`,
`kön`,
`ålder_år`,
`sökorsak`,
`vp_objektiv_prio`,
`vp_objektiv_variabel_med_högst_prio`,
`vp_mätning_prio`,
`vp_mätning_variabel_med_högst_prio`,
`ess_val`,
`prio_ess`,
`prio_total`,
`utskrivning_hänvisning_återbesök`,
`åtgärd_remiss`,
`om_lab_vilka_prover`
)
VALUES
(
:`besöksdatum`,
:`kön`,
:`ålder_år`,
:`sökorsak`,
:`vp_objektiv_prio`,
:`vp_objektiv_variabel_med_högst_prio`,
:`vp_mätning_prio`,
:`vp_mätning_variabel_med_högst_prio`,
:`ess_val`,
:`prio_ess`,
:`prio_total`,
:`utskrivning_hänvisning_återbesök`,
:`åtgärd_remiss`,
:`om_lab_vilka_prover`
)";
try {
// Get DB Objects
$db = new db();
// Connect
$db = $db->connect();
// Execute Query
$stmt = $db->prepare($sql);
$stmt->bindParam(':besöksdatum', $besöksdatum);
$stmt->bindParam(':kön', $kön);
$stmt->bindParam(':ålder_år', $ålder_år);
$stmt->bindParam(':sökorsak', $sökorsak);
$stmt->bindParam(':vp_objektiv_prio', $vp_objektiv_prio);
$stmt->bindParam(':vp_objektiv_variabel_med_högst_prio', $vp_objektiv_variabel_med_högst_prio);
$stmt->bindParam(':vp_mätning_prio', $vp_mätning_prio);
$stmt->bindParam(':vp_mätning_variabel_med_högst_prio', $vp_mätning_variabel_med_högst_prio);
$stmt->bindParam(':ess_val', $ess_val);
$stmt->bindParam(':prio_ess', $prio_ess);
$stmt->bindParam(':prio_total', $prio_total);
$stmt->bindParam(':utskrivning_hänvisning_återbesök', $utskrivning_hänvisning_återbesök);
$stmt->bindParam(':åtgärd_remiss', $åtgärd_remiss);
$stmt->bindParam(':om_lab_vilka_prover', $om_lab_vilka_prover);
$stmt->execute();
echo '{"notice": {"text": "Tranås VC Entry Added"}';
} catch(PDOEception $e) {
echo '{"error": {"text": '.$e->getMessage().'}';
}
});
We did all possible experiments on that code, you can see those suggestions in comments, but we still had the problem in POST and PUT.
I commented the $stmt->execute(); to stop the execution of the query and check, I got 200 success in rest easy, but data was not inserted. I browser the error was same. It shows that the problem is in execution. I checked that code on English letters kind of data, and it was working.
I am quite sure that I had the problem because of Swedish letter, which is non-English.
I database those columns which contain Swedish letters look like that
kön varchar(125) latin1_swedish_ci
sökorsak varchar(125) latin1_swedish_ci
Which show latin1_swedish_ci, that I want you to consider also.
I will appreciate your help, and please join this discussion. If we fix this issue it will be very good research for non-English letters issue. I google almost whole day but did not got solution.
You already use SET NAMES which is the right approach, but you need to wrap the utf8 inside a single quotation mark, as defined in the MySQL documentation
SET NAMES 'charset_name' [COLLATE 'collation_name']
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'", 'CHARSET utf8');
^ ^

SQLite3 multithread at same server

How can I perform a SQLite3 exec at the same time in PHP?
I have this code (by example):
$bd = new SQLite3("database.db");
$bd->busyTimeout(5000);
$bd->exec("INSERT into 'foo' ('data') values ('bar')");
$bd->close();
unset($bd);
And it works, but the real problem is when I connect another computer to my server and I made the insert at the same time (really, I press the key that trigger the code at the same time in both computers) and it show an error "database is locked".
I know that with the pragma WAL the database works in multithread, but it even show the error. Thank you a lot! and sorry for my bad english.
The problem is sqlite3 employs database locking, as opposed to row or column locking like mysql or postgresql. If you want to do two things at the same time try using mysql, or postgresql. In mysql you would have to create the database. Your code would then look something like this:
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$count = $conn->exec("INSERT into 'foo' ('data') values ('bar')");
$conn = null // close connection

Parsing UTF-8 Characters directly to UTF-8 Database [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 9 years ago.
Just a simple question.. I am using UTF-8 as standard in both my MySQL database and HTML file.. One thing that I don't understand is why a letter is shown differently in SQL than when I typed it. I am sure it should be placed the exact same way as I write it, when using UTF-8.
Is there a class or something that automatically keeps all posted data in UTF-8 and then posts it as it is?
Your text editor also has an effect on your character encoding. Be sure to use a text editor or IDE that you can set the character encoding to UTF-8.
Try this 1. method if not succes 2.metod. Last method i say open HTML File with notepad2 editor and change encoding from File menu to UTF8 and save. i think it will be solution;
Method
$dsn = $config ["driver"] . ':dbname=' . $config ['dbname'] . ';host=' . $config ['host'];
. ';charset=UTF-8'; //---> this is the solution
try {
$this->link = new PDO ( $dsn, $config ['user'], $config ['pass'] );
// The mysql driver ignores the charset directive in $dsn (yeah, that sucks)
if ($config ["driver"] == 'mysql')
$this->link->exec ( "set names utf8" );
}
catch ( PDOException $e ) {
die ( "Hata var : " . $e->getMessage () );
}
Other:
$encodings = array("windows-1254","utf-8", "iso-8859-9" );
$data = file_get_contents($TempSrc);
$data=mb_convert_encoding($data, 'UTF-8', mb_detect_encoding($data, $encodings));
MY SOLUTION
In case anybody experience similar problem, mine was solved by adding this line after the PDO connection , array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'").
Now the connection string looks like this:
$conn = new PDO('mysql:host=localhost;dbname=$dbname', $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));

Characters not displaying correctly on a UTF-8 website

I've done everything I can think of, but special characters are not displaying correctly on this webpage.
For example, in the database it's:
But on the site it's:
Nouveaux R�alistes
Here's everything I've checked...
The database is set to UTF-8:
The page was written in NetBeans, with the document encoding set to UTF-8:
The page header declares UTF-8:
The meta charset is set to UTF-8:
I've even added the following line to my .htacess:
But there characters are still not displaying correctly, and I get the following error from the W3C Validator:
I feel like I've attempted everything, but it still won't work. (I've even tried htmlspecialchars and htmlentities in PHP, but the page doesn't even render!)
UPDATE
As requested, here is the code I'm using:
class Exhibition {
public $exhibitionDetails;
public function __construct(Database $db, $exhibitionID){
$this->_db = $db;
$params['ExhibitionID'] = $exhibitionID;
$STH = $this->_db->prepare("SELECT *
FROM Exhibition
INNER JOIN Schedule
ON Exhibition.ExhibitionID = Schedule.ExhibitionID
WHERE Schedule.Visible = 1
AND Exhibition.ExhibitionID = :ExhibitionID;");
$STH->execute($params);
$this->exhibitionDetails = $STH->fetchAll(PDO::FETCH_ASSOC);
}
}
And...
try {
$db = new Database(SITE_ROOT."/../");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$exhibition = new Exhibition($db,$_GET['id']);
} catch (PDOException $e) {
echo "<p class='error'>ERROR: ".$e->getMessage()."</p>";
}
And finally...
<p><?php echo $exhibition->exhibitionDetails[0]["Desc"]; ?></p>
If you are using mysql_* functions:
mysql_query("SET NAMES 'utf8'");
If you are using PDO
$dsn = 'mysql:host=localhost;dbname=testdb';
$username = 'username';
$password = 'password';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$dbh = new PDO($dsn, $username, $password, $options);
It sets connection encoding.
It's been a few years since I've used PHP but back then it didn't natively support Unicode and a quick search of google tells me it still doesn't. You can still make it work though.
Here's a great link:
Encodings And Character Sets To Work With Text

Categories