I can not connect with PHP PDO - php

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!

Related

I cannot connect MySQL web server

I added a database to my cPanel, but I cannot connect it.
try{
$db = new
PDO('mysql:host=markus.veridyen.com;dbname=sosyalki_pratiki1_ipss;charset=utf8','sosyalki','password');
}catch(PDOException $e){
echo 'Hata: '.$e->getMessage();
}
When I try to connect my database, it gives me this error message:
Hata: SQLSTATE[HY000] [2002] The connection could not be established because the target machine actively refused.
Notice: Undefined variable: db in C:\xampp\htdocs\ipss\survey.php on line 55
You still can use localhost as server name on a live server.
I'll assume you are using cpanel.
<?php
$servername = "localhost";
$username = "username"; //your cpanel username
$password = "password"; //your cpanel password
try {
$conn = new PDO("mysql:host=$servername;dbname=DatabaseName", $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();
}
?>

Separating database config from connection

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.

Invalid Data Source Name - Connection to MySQL with php, PDO and DSN

This script
<?php
/* Connect to a MySQL database using driver invocation */
$dsn = 'mysqldg';
$user = 'odbc_dg';
$password = '999999999';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
gives the error *Connection failed: invalid data source name*
I have created an entry in /etc/odbc.ini as follows:
[mysqldg]
Description = DGDB
Driver = mysql537
Database = dg1
Servername = 99.99.99.99
UID = odbc_dg
PWD = 999999
SSLKeyFile = /etc/mysql/ssl/ck.pem
SSLCertFile = /etc/mysql/ssl/cc.pem
SSLCAFile = /etc/mysql/ssl/c1.pem
/etc/odbcinst.ini has the following entry:
[mysql537]
Description = MySQL driver for Plesk
Driver = /usr/lib/odbc2/lib/libmyodcb5w.so
Setup = /usr/lib/odbc2/lib/libmyodbc5w.so
The entry in odbcinst.ini works with a non-DSN connection.
I'm obviously missing something, can anyone help? Thanks.
UPDATED....
I have tried Your Common Sense's code as follows:
<?php
$host = '46.99.199.199';
$db = 'dg';
$user = 'odbc_dg';
$pass = '999999';
$charset = 'utf8mb4';
$options = array(
PDO::MYSQL_ATTR_SSL_KEY => '/etc/mysql/ssl/ck.pem',
PDO::MYSQL_ATTR_SSL_CERT => '/etc/mysql/ssl/cc.pem',
PDO::MYSQL_ATTR_SSL_CA => '/etc/mysql/ssl/c1.pem'
);
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
... but I get a connection fail message - Connection failed: SQLSTATE[HY000] [2002]
I think the problem is that the keys I have supplied only work with ODBC
For example this code, which uses odbc_connect works....
<?php
ini_set ('error_reporting', E_ALL);
ini_set ('display_errors', '1');
error_reporting (E_ALL|E_STRICT);
$user = "odbc_dg";
$pass = "99999";
$connection = "Driver= {mysql537};Server=46.99.199.199;Database=dgdb;UID=dgdb;PWD=999999;sslca=/etc/mysql/ssl/c1.pem;sslkey=/etc/mysql/ssl/ck.pem;sslcert=/etc/mysql/ssl/cc.pem";
$con = odbc_connect($connection, $user, $pass);
$sql="SELECT Id from stk_item";
$rs=odbc_exec($con,$sql);
if (!$rs) {
exit("Error in SQL");
}
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";
while (odbc_fetch_row($rs)) {
echo odbc_result($rs, "Id"), "\n";
}
odbc_close($con);
echo "</table>";
?>
My problem is that I want to connect to the remote database via pdo because that's the only type of connection allowed in the Drupal synchronising code.

Error when trying to access database on server: Lost connection to MySQL server

I am trying to access a database on my web host with a php file that is on the same server. When trying to load the page I get the following error: mysql_connect(): Lost connection to MySQL server at 'reading initial communication packet', system error: 111. I cannot find a good answer what it going wrong. Below is my php that I am using. I have my IP address of my database set as my host name.
<?php
$con = mysql_connect("10.123.0.209:3306","username", "password");
if (!$con){
die("cannot connect: " . mysql_error());
}
mysql_select_db("matmac78_macy", $con);
$sql = "SELECT * FROM countries";
$mydata = mysql_query($sql, $con);
while ($record = mysql_fetch_array($mydata)){
echo $record['country'] . " " . $record['population']
echo"<br/>";
}
mysql_close($con);
?>
Any help would be greatly appreciated!
You should switch to using PHP's PDO connection protocol.
$username = 'username';
$password = 'password';
$dbName = 'matmac78_macy';
$host = '10.123.0.209:3306';
try {
$this->database = new \PDO( "mysql:host={$this->host};dbname={$this->dbName}", $this->username, $this->password );
$this->database->setAttribute( \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION );
$this->database->setAttribute( \PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC );
return $this->database;
} catch (\PDOException $e) {
throw new \Exception( "Could not establish database connection. \n" ); #Push error message
}

SQLSTATE[HY000] [2002] Connection refused

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.

Categories