I have run into a very confusing issue with connecting to a database via PHP PDO using exec().
I have thrown together the following snippet to illustrate my point.
$host = "localhost";
$db_name = "some_db";
$user_name = "some_user";
$pass_word = "some_password";
try {
// assign PDO object to db variable
$dbh = new PDO("mysql:host=$host;dbname=$db_name;charset=utf8", $user_name, $pass_word, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
echo "yahoo connected";
}
catch (PDOException $e) {
//Output error - would normally log this to error file rather than output to user.
echo "Connection Error: " . $e->getMessage();
}
When I run this code via the browser it connects fine but when I run it at the command line it gives the following error:
Connection Error: SQLSTATE[28000] [1045] Access denied for user 'some_user'#'localhost' (using password: NO)
Needless to say that this is confusing as the password is indeed set as you can see in the code above and the connection works and prints yahoo to the screen in the browser. Any ideas are appreciated.
Your snippet is wrong. It ought to be without useless try-catch block:
$host = "localhost";
$db_name = "some_db";
$user_name = "some_user";
$pass_word = "some_password";
$dsn = "mysql:host=$host;dbname=$db_name;charset=utf8"
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
// other options
);
$dbh = new PDO($dsn, $user_name, $pass_word, $opt);
echo "yahoo connected";
this way you will get a complete error message,including stack trace which will show you the actual file you runs - in which there is empty password used.
it is also important to have error_reporting(E_ALL); to tell you possible issues with variables scope
Related
I'm trying to make a connection to the database while having the database config information saperated from the connection.
This is the code I wrote
db config information:
$config = array(
"database" => array(
"host" => "host",
"username" => "username",
"password" => "password",
"name" => "name",
)
);
define("databse_config", $config["database"]);
$config normaly also contains other information not relevant to the question ,that is why I have defined "database_config".
database connection:
require_once "config.php";
define("DB_HOST", databse_config['host']);
define("DB_USERNAME", databse_config['username']);
define("DB_PASSWORD", databse_config['password']);
define("DB_NAME", databse_config['name']);
function connect()
{
$dbhost = DB_HOST;
$dbuser = DB_USERNAME;
$dbpass = DB_PASSWORD;
$dbname = DB_NAME;
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->exec("set names utf8");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
connect();
The problem I keep running in to is that wile trying to execute the function the page keeps loading and eventualy outputs the following error:
Connection failed: SQLSTATE[HY000] [2002] Connection timed out
I'm fairly new to PDO so I also tried the same while using mysqli, which gave the same result.
Any help would be appreciated.
Connection failed: SQLSTATE[HY000] [2002] Connection timed out
This means php tried to establish a TCP/IP connection to your database server AND FAILED. You provided a DB_HOST hostname that's unreachable by network from the location of your php program.
The hostname value could be missing, or it could be wrong. If you provided it by name (mysql-server.example.com), this error message tells you the DNS name lookup succeeded.
So your php sends out a request to the server for a TCP/IP connection. That request never gets a response. That means there's a firewall somewhere blocking the connection, or that there's no network route from your php program to the network.
This all means the $dbhost value is wrong in your new PDO() operation.
Your code could be simplified a lot like this with no loss of modularity. sprintf() helps. Simpler is better for troubleshooting.
require_once "config.php";
function connect()
{
try {
$connectionString = sprintf ("mysql:host=%s;dbname=%s",
database_config['host'],
database_config['name']);
$conn = new PDO($connectionString,
database_config['username'],
database_config['password']);
$conn->exec("set names utf8");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
connect();
And you can echo $connectionString; to see what's in it, and make sure it isn't something bizarre.
I am using a Windows 10 PC which has XAMPP installed (v3.2.2).
If I do this in MySQL:
select version();
-- 10.1.32-MariaDB
That confirms the version...
I have a test database called "wp", and the username and password are both set to "wp".
I can connect to the database without a problem using PDO, but I can't connect using mysqli or mysqli_connect, and I can't see why. I've wasted a few hours on this today so far. I'm trying to install Wordpress on XAMPP but the installer says it can't connect to the database, so I have been testing around this, hence this question.
mysqli
$servername = "localhost";
$username = "wp";
$password = "wp";
$dbname = "wp";
$db = new mysqli($servername, $username, $password, $dbname);
// Warning: mysqli::__construct(): (HY000/1045): Access denied for user 'wp'#'localhost' (using password: YES) in C:\xampp\public_html\_conn.php on line 6
mysqli_connect
$host = "localhost";
$uname = "wp";
$pwd = "wp";
$dbname = "wp";
$conn = mysqli_connect($host, $uname, $pwd, $dbname);
// Warning: mysqli_connect(): (HY000/1045): Access denied for user 'wp'#'localhost' (using password: YES) in C:\xampp\public_html\_conn.php on line 13
pdo
$config['db'] = array(
'host' => 'localhost',
'username' => 'wp',
'password' => 'wp',
'dbname' => 'wp'
);
try {
$pdo = new PDO('mysql:host=' .$config['db']['host']. ';port=33066;dbname=' .$config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::NULL_EMPTY_STRING, true);
$pdo->exec("SET CHARACTER SET utf8mb4");
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
// connects fine
The wp user has the correct level of access:
Since the same user details are used to connect via PDO, but they don't work for the other methods.
I have checked using phpinfo(); and can see that mysqli is set up as far as I can see (I searched for mysqli_connect but can't see it listed):
mysqli phpinfo
Am I missing something obvious?
Try this
//This line of code connects to mysql database
define("HOST_NAME", "localhost:3306");
define("HOST_USER", "wp");
define("HOST_PASS", "wp");
define("HOST_DB", "wp");
$db = new mysqli(HOST_NAME, HOST_USER, HOST_PASS, HOST_DB);
// This line of code checks if connection error exists.
if($db->connect_error) {
echo $db->connect_errno . " " . $db->connect_error;
} else {
echo "Connection successful.";
}
I am using PDO to connect to MySQL database. The code works perfect when run in local host. However when I transfer the code to web server (of course I have changed the user name and password accordingly) the code does not work. It gives the following error
SQLSTATE[HY000] [1045] Access denied for user 'xxx_xxxxx'#'localhost' (using password: YES)
When I test connection using old deprecated API - mysql_connect() with same user name password combination, it works perfect, so I know that the user name password combination is right.
Here is my relevant code
try {
$dsn = "mysql:dbname=company_dbname; host=localhost";
$user = "company_dbuser";
$password = "MyPassword";
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
$conn = new PDO($dsn, $user, $password, $options);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Ultimately I am able to solve the problem
Here is my edited code
try {
$dsn = "mysql:dbname=company_dbname; host=localhost";
$user = 'company_dbuser';
$password = 'MyPassword';
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
$conn = new PDO($dsn, $user, $password, $options);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Please check $user and $password assignment - instead of double quote I assigned single quoted value.
Here is my code:
<?php
try{
// connect to database and select database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "spy";
$dbh_conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$dbh_conn->exec("set names utf8");
$dbh_conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
My code works as well. But I seen a similar code which checks the connection like this:
if ( !$dbh_conn ){
// Something Went Wrong
} else {
// All Fine
}
Well do I need to this ^ condition? Or using try catch is enough to check db connection?
It depends on what you set for PDO::ATTR_ERRMODE. In your case, it's set as PDO::ERRMODE_EXCEPTION, so an error will throw an Exception.
$dbh_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
This error mode however is not applied when you connect (i.e., when __constructor() is called in PDO), since a PDOException is always thrown:
PDO::__construct() will always throw a PDOException if the connection fails regardless of which PDO::ATTR_ERRMODE is currently set. Uncaught Exceptions are fatal.
You can read about the different modes here.
I´m trying to connect to a SQL Server 2008 R2 via PHP. I used the following code:
try {
$server = "servername.do.ma.in\\MSSQLSERVER";
$user = "username";
$pass = "password";
$db = "databasename";
$dbh= new PDO('sqlsrv:Server = ' . $server . '; Database = ' . $db, $user, $pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Verbindung fehlgeschlagen: ' . $e->getMessage();
}
But when i run this code i get the following error:
SQLSTATE[08001]: [Microsoft][ODBC Driver 11 for SQL Server]SQL Server Network Interfaces: Connection string is not valid [87].
Does someone know this error and know what to do?
Thanks in advance.
Solution:
The Port was not defined. The following code worked for me.
I´ve added the Port 1433 to the $server Variable.
$server = "servername.do.ma.in, 1433";
$user = "username";
$pass = "password";
$db = "databasename";
$dbh = new PDO("sqlsrv:Server={$server};Database={$db};", $user, $pass);
This will work:
$dbh = new PDO("sqlsrv:Server={$server};Database={$db};", $user, $pass);
If it's still not valid, there's something wrong with your connection variables.
EDIT:
This looks similar to your problem:
http://laravel.io/forum/01-20-2015-sql-server-2012-db-connection-with-laravel-42