i am using PDO for connecting to MYSQL database
all tables in database have utf8_unicode_ci Collation
here is my connection code :
<?php
$mysql_username = "root";
$mysql_password = "";
$mysql_host = "localhost";
$mysql_database = "cms";
try
{
//connect
global $db;
$db = new PDO('mysql:dbname=' . $mysql_database . ';host=' . $mysql_host . ';charset=utf8;', $mysql_username, $mysql_password);
$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES utf8');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex)
{
die("Unable Connect To DataBase");
}
?>
in localhost i have no problem with encoding but when i uploaded the source to a host i see ?????? instead of characters?
This:
$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES utf8');
is entirely pointless. See http://php.net/manual/en/ref.pdo-mysql.php. The MYSQL_ATTR_INIT_COMMAND is executed right after the connection is established, no later. If you set this on an already fully created PDO object, it's too late and it never executes. You need to pass it to the constructor:
new PDO(..., ..., ..., array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'))
Alternatively, if your PHP version supports it, add charset=utf8 to the DSN.
Related
I was using the PHP's define() to define constants for my PDO connection string, ie. in mysqli. However, it just didn't seem to work. I kept getting the error: Connection failed: SQLSTATE[HY000] [1045] Access denied for user 'root'#'localhost' (using password: NO) when I used the code below:
The PDO connection string would work when I didn't use PHP's define() function to pass in my connection variables. I'm using PHP 7, MySQL 8, and Apache 2.4.
Problem code below:
error_reporting(E_ALL); //check all type of errors
ini_set('display_errors', 1); // display those if any happen
//Database Connection Constant
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', 'root');
define('DB_NAME', 'gallery_db');
echo DB_PASS;
//phpinfo();
//$conn = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
try {
$dbc = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . "," . DB_USER, DB_PASS);
// set the PDO error mode to exception
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($dbc) {
echo "connected";
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Working Connection Code:
$servername = 'localhost';
$username = 'root';
$password = 'root';
$dbn = 'gallery_db';
//phpinfo();
try {
$dbc = new PDO("mysql:host=$servername;dbname=$dbn", $username, $password,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false
));
// set the PDO error mode to exception
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($dbc) {
echo "connected";
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Why does PHP define() not work in PDO's connection string?
In the first instance you try this:
$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.",". DB_USER, DB_PASS);
This only has two arguments, but PDO needs 3:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>
https://php.net/manual/en/pdo.connections.php
What happens is that your password constant works but went into the username part of the connection.
Fix:
$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
Change
$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.",". DB_USER, DB_PASS);
to
$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
Im trying to connect to odbc using the following php pdo code
$ligacao = new PDO("odbc:Driver={MYSQL ODBC 8.0 ANSI Driver };Server=localhost;Database=samsic; Uid=root;Pwd='';")
And it just gives me the following error:
Any thoughts on this?
As your database is local, as RiggsFolly said you don't need ODBC.
$db_host = "localhost";
$db_name = "samsic";
$db_user = "root";
$db_pass = "";
try{
$dbh = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'success';
}
catch(PDOException $e){
die('ERROR: ' . $e->getMessage());
}
I'm looking for a way to connect to the postgresql database using UTF8 charset.
Currently, I have to send a query request after the connexion to specify the charset. It is not optimal at all...
$connect = new \PDO("pgsql:host=$this->host;dbname=$this->base", $this->user, $this->pass);
$connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$connect->query("SET NAMES '$this->charset'");
MySQL allows to pass a table on argument to specify the charset, I'm looking for the same thing.
$this->db = new \PDO("pgsql:host=$this->PARAM_hote;dbname=$this->PARAM_nom_bd", $this->PARAM_utilisateur, $this->PARAM_mot_passe, array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
$this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
Went with :
new PDO('pgsql:host=' . $db_host . ';dbname=' . $db_name . ';options=\'--client_encoding=UTF8\'', $db_username, $db_password, array(PDO::ATTR_PERSISTENT => true));
As a matter of fact, the single quote to pass the option --client_encoding=UTF8 is very important and a double one doesn't works.
You can pass 'options' key like this:
$dbh = new PDO
(
"pgsql:dbname=mydbname;host=myhost;port=5432;options='--client_encoding=UTF8'",
"username",
"password"
);
Try add params in constructor:
$connect = new \PDO("pgsql:host=$this->host;dbname=" . $this->base . ";options='-c client_encoding=utf8'", $this->user, $this->pass);
$connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
I want to connect to mysql database using php and following is my configuration file.
<?php
$host = "localhost";
$db = "payroll"
$username ="root";
$password = "";
mysql_connect ($host,$username,$password);
mysql_select_db($db,$username);
?>
but when I run my program it gives me this error:
SQL error: No database selected SQL errno: 1046
SQL: select language, admin from user where username='admin' and password='abc123'
What's wrong with my code?
You forgot a semicolon here
$db = "payroll";
^--- Here
Don't forget to enable error reporting on your code. This is how you do it.
This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
Switch to Prepared Statements..
A kickstart example..
<?php
$dsn = 'mysql:dbname=payroll;host=localhost';
$user = 'root';
$password = '';
try
{
$dbh = new PDO($dsn, $user, $password ,array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
Read more here on PHP Manual
$mysqlhost="localhost"; // MySQL-Host
$mysqluser="user"; // MySQL-User
$mysqlpwd="password"; // Password
$connection=mysql_connect($mysqlhost, $mysqluser, $mysqlpwd) or die
("CouldnĀ“t connect");
$mysqldb="database"; // Your Database
mysql_select_db($mysqldb, $connection) or die("Couldnt select database");
I always use this. Here you get every errormessage you need to find your error.
Try this
<?php
$host = "localhost";
$db = "payroll"
$username ="root";
$password = "";
$con = mysql_connect ($host,$username,$password);
mysql_select_db($db,$con);
?>
I had this previously in my normal mysql_* connection:
mysql_set_charset("utf8",$link);
mysql_query("SET NAMES 'UTF8'");
Do I need it for the PDO? And where should I have it?
$connect = new PDO("mysql:host=$host;dbname=$db", $user, $pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
You'll have it in your connection string like:
"mysql:host=$host;dbname=$db;charset=utf8mb4"
HOWEVER, prior to PHP 5.3.6, the charset option was ignored. If you're running an older version of PHP, you must do it like this:
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
$dbh->exec("set names utf8mb4");
Prior to PHP 5.3.6, the charset option was ignored. If you're running an older version of PHP, you must do it like this:
<?php
$dbh = new PDO("mysql:$connstr", $user, $password);
$dbh -> exec("set names utf8");
?>
This is probably the most elegant way to do it.
Right in the PDO constructor call, but avoiding the buggy charset option (as mentioned above):
$connect = new PDO(
"mysql:host=$host;dbname=$db",
$user,
$pass,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
)
);
Works great for me.
For completeness, there're actually three ways to set the encoding when connecting to MySQL from PDO and which ones are available depend on your PHP version. The order of preference would be:
charset parameter in the DSN string
Run SET NAMES utf8 with PDO::MYSQL_ATTR_INIT_COMMAND connection option
Run SET NAMES utf8 manually
This sample code implements all three:
<?php
define('DB_HOST', 'localhost');
define('DB_SCHEMA', 'test');
define('DB_USER', 'test');
define('DB_PASSWORD', 'test');
define('DB_ENCODING', 'utf8');
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_SCHEMA;
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);
if( version_compare(PHP_VERSION, '5.3.6', '<') ){
if( defined('PDO::MYSQL_ATTR_INIT_COMMAND') ){
$options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . DB_ENCODING;
}
}else{
$dsn .= ';charset=' . DB_ENCODING;
}
$conn = #new PDO($dsn, DB_USER, DB_PASSWORD, $options);
if( version_compare(PHP_VERSION, '5.3.6', '<') && !defined('PDO::MYSQL_ATTR_INIT_COMMAND') ){
$sql = 'SET NAMES ' . DB_ENCODING;
$conn->exec($sql);
}
Doing all three is probably overkill (unless you're writing a class you plan to distribute or reuse).
$conn = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);
$con="";
$MODE="";
$dbhost = "localhost";
$dbuser = "root";
$dbpassword = "";
$database = "name";
$con = new PDO ( "mysql:host=$dbhost;dbname=$database", "$dbuser", "$dbpassword", array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$con->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
I think you need an additionally query because the charset option in the DSN is actually ignored. see link posted in the comment of the other answer.
Looking at how Drupal 7 is doing it in http://api.drupal.org/api/drupal/includes--database--mysql--database.inc/function/DatabaseConnection_mysql%3A%3A__construct/7:
// Force MySQL to use the UTF-8 character set. Also set the collation, if a
// certain one has been set; otherwise, MySQL defaults to 'utf8_general_ci'
// for UTF-8.
if (!empty($connection_options['collation'])) {
$this->exec('SET NAMES utf8 COLLATE ' . $connection_options['collation']);
}
else {
$this->exec('SET NAMES utf8');
}
I just want to add that you have to make sure your database is created with COLLATE utf8_general_ci or whichever collation you want to use, Else you might end up with another one than intended.
In phpmyadmin you can see the collation by clicking your database and choose operations. If you try create tables with another collation than your database, your tables will end up with the database collation anyways.
So make sure the collation for your database is right before creating tables. Hope this saves someone a few hours lol
I test this code and
$db=new PDO('mysql:host=localhost;dbname=cwDB','root','',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$sql="select * from products ";
$stmt=$db->prepare($sql);
$stmt->execute();
while($result=$stmt->fetch(PDO::FETCH_ASSOC)){
$id=$result['id'];
}
in my case, i had to add this line:
$conn->exec("set names utf8"); //Support utf8
How it will look:
$conn = new PDO("mysql:host=$servername;dbname=$db", $username, $password);
$conn->exec("set names utf8"); //Support utf8