Cannot set encoding to pdf construct - php

I'm trying to set UTF8 encoding to PDO construct, what I did for now is this:
public function __construct($dbType, $dbHost, $dbName, $dbUser, $dbPass, $charset)
{
try
{
parent::__construct($dbType . ':host=' . $dbHost . ';dbname=' . $dbName, $dbUser,
$dbPass. ';charset=' . $charset);
}
catch(PDOException $e)
{
$this->_error = $e->getMessage();
}
parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
parent::setAttribute(PDO::ATTR_PERSISTENT, true);
}
when the setAttribute line is reached I get this error:
PDO::setAttribute(): SQLSTATE[00000]: No error: PDO constructor was not called
what am I doing wrong?

Are you extending PDO? When i want to instanciate a PDO object i write this:
$pdoObj = new PDO(
'mysql:dbname=' . DB_NAME .
';host=' . HOST_NAME . ";",
USER,
PWD,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
);

Related

Connect to MySQL table using PHP (XAMPP)

I am trying to make a CRUD in PHP. Apache and MySQL is still running.
class DB
{
static private $connection;
const DB_TYPE = "mysql";
const DB_HOST = "localhost";
const DB_NAME = "crud";
const USER_NAME = "root";
const USER_PASSWORD = "";
static public function getConnection()
{
if (static::$connection == null) {
try {
static::$connection = new PDO(self::DB_TYPE . "host" . self::DB_HOST . "dbname" . self::DB_NAME . self::USER_NAME . self::USER_PASSWORD);
} catch (Exception $exception) {
throw new Exception("connection failed");
}
}
return static::$connection;
}
}
I am running on localhost:3306
phpMyAdmin is up and running
The output is in the picture
output:
Your PDO invocation looks weird.
static::$connection = new PDO(self::DB_TYPE . "host" . self::DB_HOST . "dbname" . self::DB_NAME . self::USER_NAME . self::USER_PASSWORD);
The construct for this is new PDO($dsn, $user, $password);
The dsn has this format:
mysql:dbname=testdb;host=127.0.0.1;port=3333 then , user then , password
Your dsn section seems wrong, it should be more like this:
$dsn = 'mysql:dbname='. self::DB_NAME .';host=' . self::DB_HOST ;
$user = self::USER_NAME;
$password = self::USER_PASSWORD;
$dbh = new PDO($dsn, $user, $password);
I think you forgot spaces and signs in your connection arguments
That is your syntax :
new PDO(self::DB_TYPE . "host" . self::DB_HOST . "dbname" . self::DB_NAME . self::USER_NAME . self::USER_PASSWORD);
Which give :
"mysqlhostlocalhostdbnamecrudroot"
This is the syntax from the doc :
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

Pending PDO connection - medoo php

When I change the IP of my MySQL connection and run this:
$this->pdo = new PDO($dsn, $this->username, $this->password, $this->option);
The try and catch does not work. Its does not catch that error, PDOException or general exception.
The problem is that I did not get any error or a response from PDO. It is pending for a long time.
How can I get the response immediately if there are no connections?
Full code:
case 'mysql':
if ($this->socket) {
$dsn = $type . ':unix_socket=' . $this->socket . ';dbname=' . $this->database_name;
} else {
$dsn = $type . ':host=' . $this->server . ($is_port ? ';port=' . $port : '') . ';dbname=' . $this->database_name;
}
$commands[] = 'SET SQL_MODE=ANSI_QUOTES';
if (in_array($type, explode(' ', 'mariadb mysql pgsql sybase mssql')) && $this->charset) {
$commands[] = "SET NAMES '" . $this->charset . "'";
}
//**here is the problem //
$this->pdo = new PDO($dsn, $this->username, $this->password, $this->option);
foreach ($commands as $value) {
$this->pdo->exec($value);
}
} catch (PDOException $e) {
echo "Connection to database lost";
}
catch (Exception $e) {
echo "Connection to database lost";
return;
}
even if I try from php manual
$dsn = 'mysql:host=127.0.0.2;port=3306;dbname=dbname';
$username = 'user';
$password = 'pass';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$dbh = new PDO($dsn, $username, $password, $options);

Strange PDO behavior

I'm using the following code:
try {
$this->conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
try {
$stmt = $this->conn->prepare("SELECT id, name FROM images");
if ($stmt->execute()) {
if ($stmt->rowCount() > 0)
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
else
return NULL;
}
catch(PDOException $e)
{
return $e->getMessage();
}
The code perfectly works, but when I edit my query to:
$stmt = $this->conn->prepare("SELECT id, name, description FROM images");
I obtain an empty result.
Obviously the description field exists. Obviously I tested the new query with PHPMyAdmin.
I found that:
if ($stmt->rowCount() > 0)
is TRUE and I also tried to change the fetclAll to FETCH_BOTH.
Do you have any suggestions?
EDIT: OK, I FOUND THE PROBLEM:
In a record, in the column description there was a "è". If I delete the "è", all is perfectly working. Why this happening?
The Problem was due to an accented letter in a record of the database.
The solution is the use of array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4") to set the character set of the connection to 'UTF-8 MultiByte 4' as follows:
try {
$this->conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"));
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
The reason this specific version of UTF-8 is used is explained here.

PHP Error Object of Class Could Not Be Converted to String

I am trying to create a PHP file that connects to a mysql database and inserts data into the database. I am getting these errors:
( ! ) Catchable fatal error: Object of class foo_mysqli could not be converted to string in ( ! ) Notice: Undefined variable: host in C:\wamp\www\final_kk.php on line 21
( ! ) Catchable fatal error: Object of class foo_mysqli could not be converted to string in C:\wamp\www\final_kk.php on line 21
Line 21 is the first line inside of the try. Any help would be appreciated. Thanks!
<?php
class foo_mysqli extends mysqli {
public function __construct($host, $user, $pass, $db) {
parent::__construct($host, $user, $pass, $db);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
}
}
$db = new foo_mysqli('localhost', 'root', '', 'users');
echo 'Success... ' . $db->host_info . "\n";
try {
$conn = new PDO("mysql:host=$host;dbname=$db;username=$user;password=$pass", $user, $pass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users (fname, lname,email,username,password,SSN) VALUES ('$fname', '$lname', '$email', '$uname', '$password', '$ssn')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$db->close();
?>
Okay....I made some changes based on the comments and my code now looks like this:
<?php
class foo_mysqli extends mysqli {
public function __construct($host, $user, $pass, $db) {
parent::__construct($host, $user, $pass, $db);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
}
}
$db = new foo_mysqli('localhost', 'root', '', 'users');
echo 'Success... ' . $db->host_info . "\n";
settype($host, "string");
settype($user, "string");
settype($pass, "string");
try {
$conn = new PDO("mysql:host=$host;dbname=$db, $user, $pass");
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users (fname, lname,email,username,password,SSN) VALUES ('$fname', '$lname', '$email', '$uname', '$password', '$ssn')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$db->close();
?>
This got rid of one of my errors however I still get
( ! ) Catchable fatal error: Object of class foo_mysqli could not be converted to string in C:\wamp\www\final_kk.php on line 33
please help...what am I doing wrong?
You're setting $db as an instance of a foo_mysqli() object in this line:
$db = new foo_mysqli('localhost', 'root', '', 'users');
Later in
$conn = new PDO("mysql:host=$host;dbname=$db;username=$user;password=$pass", $user, $pass);
you're using $db as a database name. It's enclosed in a double-quoted string, so PHP will attempt to interpolate it and substitute a string in the PDO connection string. Since $db is now an object, it fails.
It's not clear why you're setting up an object that extends MySQLi when you're later using a PDO object anyway.
Additionally, you haven't defined $host in the scope where you're setting up your PDO connection, so PHP reports that as undefined.
Since you know what the host and database names are you could just do this:
$conn = new PDO("mysql:host=localhost;dbname=users;", $user, $pass);

PDO and classses getting the 'PDOException' error

I am getting an error: Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)' in /home/content/........
Althought if I do it in one file, it works fine!
My php file:
<?php
require 'includes/dbc.php';
$dbc = new dbc();
$db = $dbc->openDb();
$stmt = $dbc->getAllUsers($db);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['iduser'];
}
?>
my database class:
<?php
class dbc {
public $dbserver = '';
public $dbusername = '';
public $dbpassword = '';
public $dbname = '';
function openDb() {
$db = new PDO('mysql:host=' . $dbserver . ';dbname=' . $dbname . ';charset=utf8', '' . $dbusername . '', '' . $dbpassword . '');
return $db;
}
function getAllUsers($db) {
$stmt = $db->query("SELECT * FROM user");
return $stmt;
}
}
?>
In the sample-code you provided, you're not specifying a database, user, password or host to the database connection string:
function openDb() {
$db = new PDO('mysql:host=' . $dbserver . ';dbname=' . $dbname . ';charset=utf8', '' . $dbusername . '', '' . $dbpassword . '');
return $db;
}
With invalid data, your code cannot connect and therefore you're receiving the connection-error.
As they're global to the dbc class, you'll need to use $this when accessing them (such as $this->dbserver). Try updating your code to:
function openDb() {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
return $db;
}
* Also, though you may have removed it to post the question, you don't have any of those variables set to actual values either.
You forgot to define the database settings? I always use the following to connect using the PDO class.
/** Define database propperties **/
define('DB_HOST', 'localhost', true);
define('DB_USER', 'user_db', true);
define('DB_PASS', 'yoursuperpass', true);
define('DB_DATA', 'data_www', true);
$dbInstance = new PDO('mysql:dbname='.DB_DATA.';host='.DB_HOST, DB_USER, DB_PASS);
$dbInstance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbInstance->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

Categories