I can not connect to a remote server with PDO:
public function dbConnection ($dbHost, $dbName, $dbUsername, $dbPass){
try{
$dbChain = 'mysql:host='.$dbHost.';dbname='.$dbName;
$dbh = new PDO($dbChain, $dbUsername, $dbPass);
print_r($dbh->errorInfo());
die;
...
errorInfo() only returns something if I have for instance the wrong user or password. With the right one it does not report anything, but $dbh remains empty.
errorInfo()
Array
(
[0] =>
[1] =>
[2] =>
)
$dbh
object(PDO)#5 (0) {
}
It's a remote server, but I have access using for instance MySQl Workbench, from the same machine. For the local MySQL server DB the same code works just fine.
What could be wrong with the remote connection?
Edit:
public function dbConnection ($dbHost, $dbName, $dbUsername, $dbPass){
try{
$dbChain = 'mysql:host='.$dbHost.';dbname='.$dbName;
$dbh = new PDO($dbChain, $dbUsername, $dbPass);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
echo $e->getMessage();
$errorCode = $e->getCode();
var_dump($errorCode);
}
I tried this and I get the same empty result.
object(PDO)#5 (0) {
}
Edit2: Same result.
$dbh = new PDO($dbChain, $dbUsername, $dbPass
, [PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
You should use a catch, after setting the proper error attributes, to see if there are errors -
try {
$dbChain = 'mysql:host='.$dbHost.';dbname='.$dbName;
$dbh = new PDO($dbChain, $dbUsername, $dbPass);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
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);
I am fairly new at web development; I am currently trying to create a website that allows users to Submit information and have it stored in a database. I have GoDaddy for my domain name and Hosting, and I use Google Cloud Platform for the cloud database storage.
I have successfully figured out how to store HTML form data into a local database (PhpMyAdmin); I have also successfully connected my Google Cloud instance with another local database using MySQL Workbench.
I cannot figure out how to get everything connected; do I need to connect my Google Cloud instance with GoDaddy? Should I just use GoDaddy's Database offering? I tried putting the IPv4 address of my instance as the 'hostname' in my PHP connection code, which I uploaded to GoDaddy, but it is not connecting and I don’t know why. I don't even know if this is what you are supposed to do?
I’ve read about having to allow permissions for particular IP addresses to store information, but that makes no sense to me as in the real world, I can simply go to a website, fill out a form, and my information is then sent to that company's’ remote database somewhere. That’s what I’m trying to accomplish for my website. Thank you.
PS: I'm using PHP as my server-side language.
Here is a general function that you can use to connect to a Google Cloud SQL instance:
function connectSQL( $dbProject, $dbRegion, $dbInstance, $dbIP, $dbName, $dbUsername, $dbPassword, $ssl = TRUE, $persistent = FALSE, $appEngine = FALSE ) {
// $dbProject is the project that owns the database, which may differ from the project using the database
// Create a connection
$db = NULL;
if ( $appEngine ) {
// Connect from App Engine
if ( $persistent ) {
try {
$db = new pdo( "mysql:unix_socket=/cloudsql/$dbProject:$dbRegion:$dbInstance;dbname=$dbName", $dbUsername, $dbPassword, array( PDO::ATTR_PERSISTENT => TRUE ) );
} catch(PDOException $ex) {
echoArr( $ex );
return FALSE;
}
} else {
try {
$db = new pdo( "mysql:unix_socket=/cloudsql/$dbProject:$dbRegion:$dbInstance;dbname=$dbName", $dbUsername, $dbPassword );
} catch(PDOException $ex) {
echoArr( $ex );
return FALSE;
}
}
} else {
// Connect from a non-App Engine environment (localhost, other hosting, etc.)
if ( $persistent ) {
if ( !$ssl ) {
try{
$db = new pdo( 'mysql:host='.$dbIP.':3306;dbname='.$dbName, $dbUsername, $dbPassword, array( PDO::ATTR_PERSISTENT => TRUE ) );
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $ex) {
echoArr( $ex );
return FALSE;
}
} else {
try{
$db = new pdo( 'mysql:host='.$dbIP.':3306;dbname='.$dbName, $dbUsername, $dbPassword, array(
PDO::MYSQL_ATTR_SSL_KEY=>'/path/to/client-key.pem',
PDO::MYSQL_ATTR_SSL_CERT=>'/path/to/client-cert.pem',
PDO::MYSQL_ATTR_SSL_CA=>'/path/to/server-ca.pem',
PDO::ATTR_PERSISTENT => TRUE
)
);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $ex) {
echoArr( $ex );
return FALSE;
}
}
} else {
if ( !$ssl ) {
try{
$db = new pdo( 'mysql:host='.$dbIP.':3306;dbname='.$dbName, $dbUsername, $dbPassword );
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $ex) {
echoArr( $ex );
return FALSE;
}
} else {
try{
$db = new pdo( 'mysql:host='.$dbIP.':3306;dbname='.$dbName, $dbUsername, $dbPassword, array(
PDO::MYSQL_ATTR_SSL_KEY=>'/path/to/client-key.pem',
PDO::MYSQL_ATTR_SSL_CERT=>'/path/to/client-cert.pem',
PDO::MYSQL_ATTR_SSL_CA=>'/path/to/server-ca.pem'
)
);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $ex) {
echoArr( $ex );
return FALSE;
}
}
}
}
return $db;
}
You can use this regardless of where your script is hosted.
I just tried to connect a secondary database like this example bellow but i don't know why refuse to work. Any idea?
I mention that each database connection works properly individualy.
$db_HOST = "localhost";
$db_USER = "db_user";
$db_PASS = "db_pass";
$db_NAME1 = "db_test1";
$db_NAME2= "db_test2";
$db_LINK1 = mysql_connect($db_HOST, $db_USER, $db_PASS) or die("Technical revision. Please try again later!");
mysql_select_db($db_NAME1, $db_LINK1) or die("Couldn't select database");
$db_LINK2 = mysql_connect($db_HOST, $db_USER, $db_PASS, true) or die("Technical revision. Please try again later!");
mysql_select_db($db_NAME2, $db_LINK2) or die("Couldn't select database");
Errors i get in the log file:
PHP Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /config/global/variables.php on line 27
PHP Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in config/global/hello.php on line 3
Thank you!
Do the following (with PDO instead of mysql_connect as the latter is deprecated):
$db_HOST = "localhost";
$db_USER = "db_user";
$db_PASS = "db_pass";
$db_NAME1 = "db_test1";
$db_NAME2= "db_test2";
try {
$db_LINK1 = new PDO('mysql:host='.$db_HOST.';dbname='.$db_NAME1, $db_USER, $db_PASS);
foreach($db_LINK1->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
try {
$db_LINK2 = new PDO('mysql:host='.$db_HOST.';dbname='.$db_NAME2, $db_USER, $db_PASS);
foreach($db_LINK2->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
More info here: php.net/manual/en/pdo.connections.php
If the second connection fails check the exact error message.
You should really use PDO but your code works if you use your link in your db select. For example:
$db1 = mysql_connect($hostname, $username, $password);
$db2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $db1);
mysql_select_db('database2', $db2);
that should work. You forgot to select which database should be used on every link.
I thnk I found the problem.
I forgot to change all queries accordind to the new multiple connection.
LE: Solve confirmed! Thank you all!
$dbname='database_name';
$dbuser='database_user';
$dbpass='database_password';
$dbhost='localhost';
$con = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
$con->query("SET NAMES 'utf8'");
How can I check if database_name, database_user, database_password are correct or if the database exists.
As it has been suggested, use a try/catch:
$dbname='database_name';
$dbuser='database_user';
$dbpass='database_password';
$dbhost='localhost';
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
// if you do not want to output message you can log the errors
echo $e->getMessage();
$errorCode = $e->getCode();
}
I'm trying to make a connection to sql server 2012 with php, but always shows
Erro: SQLSTATE[IMSSP]: An invalid keyword 'Databases' was specified in the DSN string.
Can someone help me with this?
here is the code that i use to make the connection
<?php
session_start();
$servername = 'SERVERNAME';
$username = 'sa';
$password = '12345678';
$dbname = 'DBNAME';
//connection
try {
$conn = new PDO("sqlsrv:server=$servername;database=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::SQLSRV_ATTR_DIRECT_QUERY , true);
} catch(PDOException $e) {
echo "Erro: " . $e->getMessage();
}
$conn=null;
?>
I haven't used SQL server 2012 but try changing
$conn = new PDO("sqlsrv:server=$servername;database=$dbname", $username, $password);
To
$conn = new PDO("mssql:host=$servername;dbname=$dbname", $username, $password);