Pending PDO connection - medoo php - 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);

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);

Combining connect data into one file

I have a PHP file that I use to include when I connect to my db. It looks something like this:
<?php
$mysqlhst = "localhost";
$database = "mydb1";
$username = "my_usr";
$password = "mypas2db1";
try {
$db = new PDO("mysql:host=$mysqlhst;dbname=$database;charset=UTF8", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
I also have a second database that I frequently access at the same time as the first one. Can I combine both connections like this or is there a better way of doing it?
<?php
$mysqlhst = "localhost";
$database = "mydb1";
$username = "my_usr1";
$password = "mypas2db1";
try {
$db = new PDO("mysql:host=$mysqlhst;dbname=$database;charset=UTF8", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$database = "mydb2";
$username = "my_usr2";
$password = "mypas2db2";
try {
$db2 = new PDO("mysql:host=$mysqlhst;dbname=$database;charset=UTF8", $username, $password);
$db2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Assuming you're not using Classes, you could DRY (Do-not Repeat Yourself) up your code a little like the following. This allows for extending into even further databases/users/servers in the future if required:
<?php
$connections = [
'db1' => [
'host' = 'localhost';
'database' = 'mydb1';
'username' = 'my_usr1';
'password' = 'mypas2db1';
],
'db2' => [
'host' = 'localhost';
'database' = 'mydb2';
'username' = 'my_usr2';
'password' = 'mypas2db2';
],
];
function getDatabaseConnection($connectionName = 'db1'): ?PDO
{
global $connections;
if (empty($connections[$connectionName]) {
// Throw an exception because this connection doesn't exist.
throw new \Exception(
"Connection: {$connectionName} not specified."
);
}
$data = $connections[$connectionName];
$dbHost = $data['host'] ?: 'localhost';
$dbUsername = $data['username'] ?: '';
$dbPassword = $data['password'] ?: '';
$dbName = $data['database'] ?: '';
if (!$dbUsername || !$dbName) {
// We don't have a username or database to connect to. Fail.
throw new \Exception(
'No valid database name or user provided.'
);
}
$db = new PDO(
"mysql:host={$dbHost};dbname={$dbName};charset=UTF8",
$dbUsername,
$dbPassword
);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
// We don't need to specify a connection because we want the default, db1.
$db1 = getDatabaseConnection();
// Specify we want a connection to db2.
$db2 = getDatabaseConnection('db2');

how can i transform mysql to PDO connection?

How can I transform the mysql code bellow into pdo connection ? because i have some networking issues.
$gaSql['user'] = "root";
$gaSql['password'] = "";
$gaSql['db'] = "test";
$gaSql['server'] = "localhost";
// DB connection
function dbinit(&$gaSql) {
// if error rezults 500
function fatal_error($sErrorMessage = '') {
header($_SERVER['SERVER_PROTOCOL'] .' 500 Internal Server Error');
die($sErrorMessage);
}
// connecting to mysql
if ( !$gaSql['link'] = #mysql_connect($gaSql['server'], $gaSql['user'], $gaSql['password']) ) {
fatal_error('Could not open connection to server');
}
// select the DB
if ( !mysql_select_db($gaSql['db'], $gaSql['link']) ) {
fatal_error('Could not select database');
}
}
Proper PDO db connection
<?php
$host = '127.0.0.1';
$db = 'your db';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dbh = new PDO($dsn, $user, $pass, $options);
?>
Reference : https://phpdelusions.net/pdo
I use this in all my pdo connections it works perfectly
You could try something like this:
try {
$pdo = new PDO('mysql:host=' . $gaSql['server'] . ';dbname=' . $gaSql['db'], $gaSql['user'], $gaSql['password']);
} catch (PDOException $ex) {
if ($ex->getCode() == 1049) {
throw new Exception('Unknown Database: ' . $gaSql['db']);
} elseif ($ex->getCode() == 1045) {
throw new Exception('Wrong credentials for user: ' . $gaSql['user']);
}
}
Hope, this helps ;-)

Cannot set encoding to pdf construct

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")
);

PDO Inserts Duplicate Data in MySQL

I have the following code and whenever the function is called it is inserting the data twice.
The php that is calling the class/function:
$add_amenity = new listing;
echo $add_amenity->add_amenity($_POST['name']);
Here is the function:
public function add_amenity($a)
{
try {
$dbh = new PDO("mysql:host=" . db_host . ";dbname=" . db_name . "",db_user,db_password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $dbh->prepare("INSERT INTO amenitylist (id,name,icon,isactive) VALUES ('',:a,'','1')");
$q->bindParam(':a', $a);
$q->execute();
$this->_results = $dbh->lastInsertId();
} catch(PDOException $e) {
$this->_results = "ERROR: " . $e->getMessage();
}
}

Categories