Unable To Connect Database MySql - php

I'm New To PHP PDO and I have written following Code on Config.php
class DBConnect{
/* defining constants for database connectivity */
private $host="127.0.0.1";
private $user="root";
private $pass="";
private $dbname="sms-portal";
private $dbh;
private $error;
public function __construct(){
// set DSN
$dsn='mysql:host='.$this->host.'dbname='.$this->dbname;
//set Options
$options= array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create New PDO instance
try{
$this->dbh=new PDO($dsn, $this->user, $this->pass, $options);
//die("here");
}
// Catch any errors here
catch(PDOException $e){
$this->error=$e->getMessage();
}
}
}
Whilst working on localhost and Submitting NewUserRegistration form Its Showing Me following Warning Message.
Warning: PDO::__construct() [pdo.--construct]:
php_network_getaddresses: getaddrinfo failed:
No such host is known. in config.php on line 25
Warning: PDO::__construct() [pdo.--construct]:
[2002] php_network_getaddresses: getaddrinfo failed:
No such host is kn (trying to connect via tcp://127.0.0.1dbname=sms-portal:3306)
in config.php on line 25

$dsn='mysql:host='.$this->host.'dbname='.$this->dbname;
Looks like you are missing a semicolon before dbname= - try this:
$dsn='mysql:host='.$this->host.';dbname='.$this->dbname;

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
Note : You just missed ";" between host and dbname.

Add the ; semicolon before the dbname:
$dsn='mysql:host='.$this->host.';dbname='.$this->dbname;
// ^ this one
If you look at the error, the host isn't terminated well:
tcp://127.0.0.1dbname=sms-portal:3306

Related

Uncaught TypeError: PDO::__construct() expects parameter 1 to be string

I have searched the forum, but I have not found anything directly related to my issue. I am fairly new to PDOs and class OOP creation. I am trying to create a database connection class where I can instantiate the connection as needed. I having issues instantiating my connection.
File Organization:
parent directory (folder)
|
private (folder)
|
config.php
classes (folder)
|
class1.class.php
DatabaseConnection.class.php
db_cred.inc.php
public (folder)
|
search.php
Process:
I have created a database credential php file "db_cred.inc.php"
I have a database connection class called "DatabaseConnect" in "DatabaseConnect.class.php" file
I load those files as follows
require_once 'db_cred.inc.php'; in the "DatabaseConnect.class.php" file
spl_autoload_register for all of my class files
Expected actions:
When my "search.php" page request data from mysql via a pdo, a new database connection will instantiate a new connection via the "openConnection()" method.
The class "DatabaseConnection" will load the credentials from "db_cred.inc.php" as a sting and connect to the database
The class will then use the credentials to connect to the mysql database, and execute the requested pdo query returning the results and storing them into a variable "$row".
Issue:
When I execute the pdo, the following error is returned:
Uncaught TypeError: PDO::__construct() expects parameter 1 to be string, array given in private/classes/DatabaseConnect.class.php:21 Stack trace: #0 private\classes\DatabaseConnect.class.php(21): PDO->__construct(Array) #1 \public\search.php(53): DatabaseConnect->openConnection() #2 {main} thrown in \private\classes\DatabaseConnect.class.php on line 21
spl_autoload_register() in the config.php file
function my_autoload($class) {
if(preg_match('/\A\w+\Z/', $class)) {
require ('classes/' . $class . '.class.php');
}
}
spl_autoload_register('my_autoload');
Credential setup in "db_cred.inc.php"
<?php
// define an array for db connection.
define("DB", [
"DB_HOST" => "mysql:host=localhost",
"DB_USER" => "user",
"DB_PASS" => "pass",
"DB_DATABASE" => "mytestdb",
"DB_CHAR" => "utf8",
]);
?>
My class for database connection:
<?php
require_once 'db_cred.inc.php';
// creating db connection class
class DatabaseConnect {
private $server = 'DB_HOST';
private $database = 'DB_DATABASE';
private $pass = 'DB_PASS';
private $user = 'DB_USER';
private $opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
protected $con;
public function openConnection() {
**ERROR TAKES PLACE HERE**
try {
$this->con = new PDO([$this->server, $this->database, $this->user, $this->pass]);
return $this->con;
} catch(PDOExeption $e){
echo "ERROR: " . $e->getMessage(), (int)$e->getCode();
}
}
public function closeConnection() {
$this->con = null;
}
}
?>
PDO for search.php
<?php
$dbconn = new DatabaseConnect();
$pdo = $dbconn->openConnection();
$sql = "SELECT * FROM report";
foreach ($pdo->query($sql) as $row) {
echo " PI: ".$row['pi'] . "<br>";
}
?>
I am not sure what is causing the error. I am sure it is due to my inexperience with classes and oop. It appears that the config.php file is working fine. The class is identified by the request because the error happens inside the PDO __construct method. Please help.
UPDATE - MY WORKING SOLUTION
I hope this might help someone moving forward with a similar question. I am not finished with the development of this process, but this kicked in a huge door.
My revised class
<?php
// Associating db_cred.inc.php with class
require_once('db_cred.inc.php');
// Creating db connection class
class DatabaseConnect {
/*
!! Assigning defined constants per define('DB_CONSTANT', 'value') loaded from "db_cred.inc.php" file to variables
!! "db_cred.inc.php" should not be loaded into the "config.php" file
!! BECAUSE THE VALUES OF THE VARIABLES ($variable) ARE CONSTANTS (DB_CONSTANT), DO NOT USE SINGLE OR DOUBLE QUOTES. THE PDO __CONSTRUCT FUNCTION WILL IGNORE THE VALUE OF THE VARIABLE
*/
private $host = DB_HOST;
private $database = DB_DATABASE;
private $pass = DB_PASS;
private $user = DB_USER;
private $char = DB_CHAR;
// Setting attributes and storing in variable $opt
private $opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// $con variable will store PDO connection and is set to NULL
private $con;
// Create Connection to database
public function openConnection() {
// Setting $con to null
$this->con = NULL;
// If $con is not NULL make it NULL
if ($this->con === NULL){
try {
// Establish DSN
$dsn = "mysql:host={$this->host};dbname={$this->database};charset={$this->char}";
// Complete the PDO connection
$this->con = new PDO($dsn, $this->user, $this->pass,$this->opt);
// Return the connection and store it in $con
return $this->con;
// Catch any exceptions and store in $e
} catch(PDOExeption $e){
// Echo error and Exception message
echo "ERROR: " . $e->getMessage(), (int)$e->getCode();
}
// If the try/catch block fails, echo that no connection was established
} else {
echo "ERROR: No connection can be established";
}
}
// Close connection and set it to NULL
public function closeConnection() {
if($this->con !== NULL){
$this->con = NULL;
}
}
// create CRUD subclass (Create, Read, Update, Delete)
}
?>
I changed "db_cred.inc.php" eliminating the array. I may revisit the idea.
<?php
// defining DB Credential CONSTANTS to be stored in variables and instantiated by connect class
define("DB_HOST", "localhost");
define("DB_USER", "user");
define("DB_PASS", "pass");
define("DB_DATABASE", "mytestdb");
define("DB_CHAR", "utf8");
// define an array for db connection.
/*define("DB", [
"DB_HOST" => "localhost",
"DB_USER" => "user",
"DB_PASS" => "pass",
"DB_DATABASE" => "mytestdb",
"DB_CHAR" => "utf8",
]);*/
?>
The error explains itself: You're passing an array where you should be using a string instead.
You need to change this line:
$this->con = new PDO([$this->server, $this->database, $this->user, $this->pass]);
To this, (specifies the DSN first):
$dsn = "mysql:dbname={$this->database};host:{$this->host}";
$this->con = new PDO($dsn, $this->user, $this->password);

DB connection Error In PHP Slim framework in mac Connection failed: SQLSTATE[HY000] [2002] Connection timed out

I have installed Xampp VM in mac for PHP slim framework(V3).
get an error when try to connect remote db over the internet using vpn.
error is Connection failed: SQLSTATE[HY000] [2002] Connection timed out
but xampp local db connect without any error.
I used this code for connecting.
class db
{
public $dbhost = '192.168.1.78';
public $dbuser = 'root';
public $dbpass = 'Raven898';
public $dbname = 'xyz';
public $dbport = '3306';
// Connect
public function connect()
{
$connection = 'mysql:host='.$this->dbhost.';dbname='.$this->dbname;
try {
$dbh = new PDO($connection, $this->dbuser, $this->dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: '.$e->getMessage();
}
}
}

Unable to connect PHP application with MySQL

From a friend, I got a website (zip file) with PHP and HTML files in it. I also got a SQL script from him. Now what I'm trying to do is run the application on localhost (Xampp apache server) and the website does load, but it looks like I can't connect to the database.(I did import the SQL script and it worked, But I'm still getting this error) This is an error for example that I'm receiving on the home page:
Connection failed: SQLSTATE[HY000] [1045] Access denied for user 'dewaai'#'localhost' (using password: YES)
Notice: Undefined index: logged in C:\xampp\htdocs\deWaai\includes\header.php on line 14
The name of the database is 'dewaai'
The username is: root
And I think there is no password...
This is the connection.php file:
<?php
session_start();
include "db.php";
$db = new db();
$db->setDB("localhost", "dewaai", "dewaai", "dewaai");
$db->connect();
?>
These are database functions in the db.php file:
<?php
class db {
private $conn;
private $servername;
private $dbuser;
private $dbpass;
private $dbname;
function setDB($servername, $dbuser, $dbpass, $dbname) {
$this->servername = $servername;
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
$this->dbname = $dbname;
}
function connect() {
try {
$this->conn = new PDO("mysql:host=$this->servername;dbname=$this->dbname", $this->dbuser, $this->dbpass);
// set the PDO error mode to exception
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
Does anyone know how I can fix this so the database runs the application?
I really don't know why I'm getting that error.
Any kind of help is appreciated, thx
There is problem with your username or password.
$db->setDB("localhost", "root", "", "dewaai");
Try this it will help you to connect with your database
Hi the issue clearly from the error message states that your username and password given in connection.php file is incorrect.
The format for DB connection is
$db->setDB( Database host IP address or DNS name , Username , Password, DatabaseName);
From what you said i guess connection.php file should be
<?php
session_start();
include "db.php";
$db = new db();
$db->setDB("localhost", "root", "", "dewaai");
$db->connect();
?>
And i think your PDO connection might have an issue as well. It should be
$this->conn = new PDO('mysql:host='.$this->servername.'; dbname='.$this->dbname, $this->dbuser, $this->dbpass);
Hope this helps.

How to get PHP and PDO working in Godaddy shared hosting?

I have a fatal error showing when I am trying to get MySQL to use a PDO instance in Godaddy shared hosting.
Code I tried to connect my database:
code 1
try{
$connect = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'user', 'password',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die('Error connecting to database');
}
When I used this code, it is printing 'Error connecting to database'
code 2
$dsn = 'mysql:host=localhost;dbname=dbname';
$user = 'user';
$password = 'password';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
When I used this code it is printing an error:
'Connection failed: SQLSTATE[HY000] [1044] Access denied for user 'user'#'localhost' to database 'dbname"
Godaddy support is saying it is a string error that I have to review from my end and they are asking paid service to resolve it from their end. I found this both code running in my local server (xaamp).
First, make sure everything is correct in your config array, then add '\' this before PDO instance:
// Define Config Options
$config = [
'username' => 'YourUsername',
'password' => 'YourPassword',
'database' => 'YourDatabase'
];
// Make a function to easily access it
function connect($config)
{
try{
$conn = new \PDO('mysql:host=localhost;dbname=' .$config['database'], $config['username'], $config['password']);
$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return $conn;
}
catch(Exception $e){
return false;
}
}
In shared hosting you normally find that the mysql server is not localhost, you normally find that your provider will place the mysql server on a separate machine.
Login in to you control panel with godaddy and look at the settings, you'll probably have to create a database first.

is config.php bad filename?

This examples are from lynda php beyond basic
config.php
<?php
defined('DB_SERVER') ? null : define("DB_SERVER", "localhost");
defined('DB_USER') ? null : define("DB_USER", "root");
defined('DB_PASS') ? null : define("DB_PASS", "");
defined('DB_NAME') ? null : define("DB_NAME", "photo_gallery");
?>
database.php
<?php
require_once('config.php');
class MySQLDatabase {
private $connection;
function __construct(){
$this->open_connection();
}
public function open_connection(){
$this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if (!$this->connection) {
die("Database connection failed: " . mysql_error());
} else {
$db_select = mysql_select_db(DB_NAME, $this->connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
}
}
public function close_connection(){
if(isset($this->connection)) {
mysql_close($this->connection);
unset($connection);
}
}
public function query($sql) {
$result = mysql_query($sql, $this->connection);
$this->confirm_query($result);
return $result;
}
private function confirm_query($result){
if (!$result) {
die("Database query failed: " . mysql_error());
}
}
}
$database = new MySQLDatabase();
?>
index.php
<?php
require_once("../includes/database.php");
if (isset($database)) {
echo "true";
} else {
echo "false";
}
?>
Now here my problem when I tried index.php run it on the browser i get an error
error says:
Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config.php on line 80
Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config.php on line 166
Notice: Use of undefined constant DB_SERVER - assumed 'DB_SERVER' in C:\xampp\htdocs\photo_gallery\includes\database.php on line 13
Notice: Use of undefined constant DB_USER - assumed 'DB_USER' in C:\xampp\htdocs\photo_gallery\includes\database.php on line 13
Notice: Use of undefined constant DB_PASS - assumed 'DB_PASS' in C:\xampp\htdocs\photo_gallery\includes\database.php on line 13
Warning: mysql_connect() [function.mysql-connect]: php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\photo_gallery\includes\database.php on line 13
Warning: mysql_connect() [function.mysql-connect]: [2002] php_network_getaddresses: getaddrinfo failed: No such host is known. (trying to connect via tcp://DB_SERVER:3306) in C:\xampp\htdocs\photo_gallery\includes\database.php on line 13
Warning: mysql_connect() [function.mysql-connect]: php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\photo_gallery\includes\database.php on line 13
Database connection failed: php_network_getaddresses: getaddrinfo failed: No such host is known.
I somehow fix the error by renaming config.php
So here's my question why i got this error? is config.php filename the problem?
The video tutorial from Lynda php beyond basics didn't get this error.
There is some sort of error with your local configuration, maybe because you have some third party PEAR installed, hence the error message:
Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config.php on line 166
You should revise what packages and libraries your system use, because this error message is a sign of outdated code (Deprecated). Personally, I use XAMPP on Windows with my project also having config.php in its htdocs folder without any sorts of error like these. The problem is that the linked file is for php4. On my system, the 166th line reads as follows:
$this->container = new Config_Container('section', 'root');
config.php is a conventional and general name of calling the configuration file, there is no problem with it. Keeping it with this name lowers no security barriers which could be fixed by merely renaming it.
The other errors will be fixed if your project succeeds in loading the configuration file. Also:
Warning:
Please, don't use mysql_* functions to write new code. They are no longer maintained and the community has begun the deprecation process. See the red box?
Instead, you should learn about prepared statements and use either PDO or MySQLi. This article should give some details about deciding which API to use. For PDO, here is a good tutorial.
It might be due to presence of "config.php" and "Config.php" files in same directory.
In windows,file names are not case sensitive.
In linux, they are.

Categories