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.
Related
I have a website hosted by united domains. It was working fine with MySQLi but I changed it to PDO. Now I cannot get the database to work. I've tried changing $host to 127.0.0.1, and to localhost. If I use localhost, I get the error SQLSTATE[HY000] [2002] No such file or directory.
If I use 127.0.0.1 I get SQLSTATE[HY000] [2002] Connection refused.
I have also tried by changing collation but it still doesn't work. It works perfectly fine on my other domain that is on Hostinger.
$host = "localhost"; // I have tried using both 127.0.0.1 and localhost here
$db = "db_name"; //db name goes here
$username = "username"; //username goes here
$password = "password"; //password goes
try {
//Creating a PDO instance
$conn = new PDO("mysql:host=$host;dbname=$db", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
}catch(\PDOException $e){
// if connection fails, show PDO error
echo "Connection Failed: ". $e->getMessage();
}
I'm able to connect phymyadmin of remote pc, but when i try to connect to remote db, I'm getting connection refused error.
I have seen similar kind of question, but not yet answered also it is not active now.SQLSTATE[HY000] [2002] Connection refused with right port
<?php
$servername = "192.168.1.12";
$username = "root";
$password = "root";
try {
$conn = new \PDO("mysql:host=$servername;dbname=my_db", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(\PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
In remote pc, bind address in mysql configuration file was set to 127.0.0.1 instead of 192.168.1.12
I am trying to create a simple mailing list webpage. Using LAMP. Here is the code I have for connecting to my database:
<?php
function insert()
{
$servername = "127.0.0.1";
$username = "root";
$password = "(my password here)";
$dbname = "(my db name here)";
try
{
// preparing database handle $dbh
$dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo ("Could not connect to server.\n");
echo ("getMessage(): " . $e->getMessage () . "\n");
}
}
?>
The function continues after that but this connection attempt gets cung up on the catch, and throws the "SQLSTATE[HY000] [2002] Connection refused" error. I have tried:
-Changing the $servername to localhost, but this gives me a different error: "SQLSTATE[HY000] [2002] No such file or directory"
-trying to specify all different ports
-checked all my info, database name and password.
-I can log into phpmyadmin and see that my database is fine
-looked at all other questions on this topic, with no help found.
In my PHP apicación I connect to a MySQL database with PDO, but I'm having the following problem, the error message;
Warning: PDO :: __construct () [pdo. - Construct]: [2002]
"No connection Could be made Actively Because the target machine refused it."
(trying to connect via tcp :/ / localhost: 3306)
Fatal error: Uncaught exception 'Exception' with message 'Connection failed: SQLSTATE [HY000] [2002]
The code to access the database is:
private $db = NULL;
const DB_SERVER = "localhost";
const DB_USER = "root";
const DB_PASSWORD = "usbw";
const DB_NAME = "status_poster";
public function __construct() {
//**below the error here!!**
$dsn = 'mysql:dbname=' . self::DB_NAME . ';host=' . self::DB_SERVER;//
//var_dump($dsn);
try {
$this->db = new PDO($dsn, self::DB_USER, self::DB_PASSWORD);
} catch (PDOException $e) {
throw new Exception('Connection failed: ' . $e->getMessage());
}
return $this->db;
}
What I find strange is that the same parameters to connect to "mysqli" I have no problems and I connect successfully, run CRUD statements and no problems, the code is as follows;
The code
function getProducts() {
$products = array();
$mysqli = new mysqli("localhost", "root", "usbw", "Datos");
if (mysqli_connect_errno()) {
printf("Error in conection: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Id,sku,name,price FROM products";
if ($result = $mysqli->query($query)) {
while ($obj = mysqli_fetch_object($result)) {
//instructions...
}
}
$mysqli->close();
return $products;
}
Well, I need to connect with PDO but I can not find the solution,
waiting for suggestions or help!
Sorry, can not find in the forum how to respond with a picture, but is this;
solve my problem, change the port from 3307-3306 (3306 was the port that went out in error) of USBWebserver. now work!
note: above the port was 3307
solve my problem, change the port from 3307-3306 (3306 was the port that went out in error) of USBWebserver. now work!
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