i'm new to OOP so i'm following a tutorial. so in that it uses following codes to connect to the database but in my case it is not connecting
databas.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($this->connection);
}
}
public function query($sql) {
$result = mysql_query($sql, $this->connection);
$this->confirm_query($result);
return $result;
}
public function mysql_prep( $value ) {
$magic_quotes_active = get_magic_quotes_gpc();
$new_enough_php = function_exists( "mysql_real_escape_string" ); // i.e. PHP >= v4.3.0
if( $new_enough_php ) { // PHP v4.3.0 or higher
// undo any magic quote effects so mysql_real_escape_string can do the work
if( $magic_quotes_active ) { $value = stripslashes( $value ); }
$value = mysql_real_escape_string( $value );
} else { // before PHP v4.3.0
// if magic quotes aren't already on then add slashes manually
if( !$magic_quotes_active ) { $value = addslashes( $value ); }
// if magic quotes are active, then the slashes already exist
}
return $value;
}
private function confirm_query($result) {
if (!$result) {
die("Database query failed: " . mysql_error());
}
}
}
$database =& new MySQLDatabase();
$db =& $database;
?>
config.php
<?php
// Database Constants
defined('DB_SERVER') ? null : define("DB_SERVER", "localhost");
defined('DB_USER') ? null : define("DB_USER", "oop_project");
defined('DB_PASS') ? null : define("DB_PASS", "");
defined('DB_NAME') ? null : define("DB_NAME", "oop_project");
?>
function.php
<?php
function strip_zeros_from_date( $marked_string="" ) {
// first remove the marked zeros
$no_zeros = str_replace('*0', '', $marked_string);
// then remove any remaining marks
$cleaned_string = str_replace('*', '', $no_zeros);
return $cleaned_string;
}
function redirect_to( $location = NULL ) {
if ($location != NULL) {
header("Location: {$location}");
exit;
}
}
function output_message($message="") {
if (!empty($message)) {
return "<p class=\"message\">{$message}</p>";
} else {
return "";
}
}
?>
when i going to test the connection
i got these errors.
Deprecated: Assigning the return value of new by reference is deprecated in J:\xampp\htdocs\oop_project\includes\database.php on line 60
Deprecated: Assigning the return value of new by reference is deprecated in J:\xampp\php\PEAR\Config.php on line 80
Deprecated: Assigning the return value of new by reference is deprecated in J:\xampp\php\PEAR\Config.php on line 166
Notice: Use of undefined constant DB_SERVER - assumed 'DB_SERVER' in J:\xampp\htdocs\oop_project\includes\database.php on line 13
Notice: Use of undefined constant DB_USER - assumed 'DB_USER' in J:\xampp\htdocs\oop_project\includes\database.php on line 13
Notice: Use of undefined constant DB_PASS - assumed 'DB_PASS' in J:\xampp\htdocs\oop_project\includes\database.php on line 13
Warning: mysql_connect() [function.mysql-connect]: php_network_getaddresses: getaddrinfo failed: No such host is known. in J:\xampp\htdocs\oop_project\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 J:\xampp\htdocs\oop_project\includes\database.php on line 13
Warning: mysql_connect() [function.mysql-connect]: php_network_getaddresses: getaddrinfo failed: No such host is known. in J:\xampp\htdocs\oop_project\includes\database.php on line 13
Database connection failed: php_network_getaddresses: getaddrinfo failed: No such host is known.
how can i correct this...? thank you.
The "deprecated" warnings are because you're using
$database =& new MySQLDatabase();
replace with
$database = new MySQLDatabase();
The notices are because it seems the constants (DB_SERVER, ...) are not defined before you try and instantiate the class (new MySQLDatabase). Make sure config.php is loaded before.
The other warnings are connected to those same issues.
The include for config.php is actually including
J:\xampp\php\PEAR\Config.php
not your local config file.
It seems that something is incorrect with your DB_SERVER, DB_USER, DB_PASS variables or something is wrong with your server? You should definitely invest time in trying the example without your deprecated oop classes.
But, first try changing your $database =& new MySQLDatabase();
to a cleaner $database = new MySQLDatabase();
If you wanted to move over to PDO then here is a quick example of what I think your trying to achieve. A CreateReadUpdateDelete (CRUD) class.
<?php
class MySQLDatabase{
public $db;
function __construct($dsn, $user=null, $pass=null){
$this->dsn = $dsn;
$this->user = $user;
$this->pass = $pass;
//Connect
$this->connect();
}
function connect(){
try{
$this->db = new PDO($this->dsn, $this->user, $this->pass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch (Exception $e){
die('Cannot connect to databse. Details:'.$e->getMessage());
}
}
function Select($table, $fieldname=null, $fieldvalue=null){
$sql = "SELECT * FROM $table";
$sql .=($fieldname != null && $fieldvalue != null)?" WHERE $fieldname=:id":null;
$statement = $this->db->prepare($sql);
if($fieldname != null && $fieldvalue != null){$statement->bindParam(':id', $fieldvalue);}
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
function Insert($table, $values){
$fieldnames = array_keys($values[0]);
$sql = "INSERT INTO $table";
$fields = '( ' . implode(' ,', $fieldnames) . ' )';
$bound = '(:' . implode(', :', $fieldnames) . ' )';
$sql .= $fields.' VALUES '.$bound;
$statement = $this->db->prepare($sql);
foreach($values as $vals){
$statement->execute($vals);
}
}
function Update($table, $fieldname, $value, $where_key, $id){
$sql = "UPDATE `$table` SET `$fieldname`= :value WHERE `$where_key` = :id";
$statement = $this->db->prepare($sql);
$statement->bindParam(':id', $id);
$statement->bindParam(':value', $value);
$statement->execute();
}
function Delete($table, $fieldname=null, $id=null){
$sql = "DELETE FROM `$table`";
$sql .=($fieldname != null && $id != null)?" WHERE $fieldname=:id":null;
$statement = $this->db->prepare($sql);
if($fieldname != null && $id != null){$statement->bindParam(':id', $id);}
$statement->execute();
}
}
//Sample Usage
$db = new MySQLDatabase('mysql:host=localhost;dbname=test','root','password');
//Multi insert:
$insert = array(array('some_col'=>'This was inserted by the $db->Insert() method'),
array('some_col'=>'Test insert 2'),
array('some_col'=>'Test insert 3'),
);
$db->Insert('pdo_test', $insert);
//Select All
$result = $db->Select('pdo_test');
/*
Array
(
[0] => Array
(
[id] => 2
[some_col] => This was inserted by the $db->Insert() method
)
[1] => Array
(
[id] => 3
[some_col] => Test insert 2
)
[2] => Array
(
[id] => 4
[some_col] => Test insert 3
)
)
*/
//Single select
$result = $db->Select('pdo_test','id','2');
/*
Array
(
[0] => Array
(
[id] => 2
[some_col] => This was inserted by the $db->Insert() method
)
)
*/
/* Delete Single record*/
$db->Delete('pdo_test', 'id', '2');
/*Delete All*/
$db->Delete('pdo_test');
//Array ( )
$result = $db->Select('pdo_test');
?>
Best solution is goto php.ini
allow_url_include = On
and save
or
use
inlcude 'J:\xampp\htdocs\oop_project\includes\database.php';
require_once 'J:\xampp\htdocs\oop_project\includes\database.php';
As per require this will resolve the
php_network_getaddresses: getaddrinfo failed: No such host is known.
Related
Hey for some reason i will use the try keyword in php to catch the PDO exception but it wont. I would put random incorrect details and it shows PDO Uncaught Exception and it show the connection details. It works i can execute the sql statements but when the conn details are incorrect it says uncaught PDO exception. This is for a framework i am working on.
the global file calls all the other files but il only include the database classes because thats where the problem is.
Global.php
<?php
namespace App\Framework;
define('APP_VERSION', '1.0.0');
defined("START") ? null : define("START", microtime());
define('DEBUG', true);
if (DEBUG) {
error_reporting(E_ALL);
ini_set('display_errors', 1);
} else {
error_reporting(0);
ini_set('display_errors', 0);
}
include_once 'LinkConfig.php';
include_once 'LinkInterface.php';
include_once 'Link.php';
try {
$Link = new Link(
LinkConfig::DRIVER,
LinkConfig::HOST,
LinkConfig::DBNAME,
LinkConfig::USER,
LinkConfig::PASS,
LinkConfig::CHARSET,
LinkConfig::PORT
);
} catch (PDOException $Exception) {
die('Connection failed: ' . $Exception->getMessage());
}
?>
This is the DB connection interface file
LinkInterface.php
<?php
namespace App\Framework;
defined('START') || (header('HTTP/1.1 403 Forbidden') & die('403.14 - Directory listing denied.'));
interface ILink {
public function __construct($Driver, $Host, $DBName, $User, $Pass, $Charset, $Port);
public function Select($Sql, $Array = array(), $FetchMode = PDO::FETCH_ASSOC);
public function Insert($Table, array $Data);
public function Update($Table, $Data, $Where, $WhereBindArray = array());
public function Delete($Table, $Where, $Bind = array(), $Limit = null);
}
?>
This is the DB connection config file.
LinkConfig.php
<?php
namespace App\Framework;
defined('START') || (header('HTTP/1.1 403 Forbidden') & die('403.14 - Directory listing denied.'));
class LinkConfig {
const DRIVER = 'mysql';
const HOST = 'localhost';
const DBNAME = 'test';
const USER = 'root';
const PASS = '';
const CHARSET = 'utf8';
const PORT = '3306';
const DEBUG = true;
}
?>
And the last file is where it all happens.
Link.php
<?php
namespace App\Framework;
defined('START') || (header('HTTP/1.1 403 Forbidden') & die('403.14 - Directory listing denied.'));
use \PDO;
class Link extends PDO {
public function __construct($Driver, $Host, $DBName, $User, $Pass, $Charset, $Port) {
parent::__construct($Driver . ':host=' . $Host . ';port=' . $Port . ';dbname=' . $DBName . ';charset=' . $Charset, $User, $Pass);
$this->exec('SET CHARACTER SET ' . $Charset);
if (LinkConfig::DEBUG) {
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
}
public function Select($Sql, $Array = array(), $FetchMode = PDO::FETCH_ASSOC) {
$Sth = $this->prepare($Sql);
foreach ($Array as $Key => $Value) {
$Sth->bindValue(":$Key", $Value);
}
$Sth->execute();
return $Sth->fetchAll($FetchMode);
}
public function Insert($Table, array $Data) {
ksort($Data);
$FieldNames = implode('`, `', array_keys($Data));
$FieldValues = ':' . implode(', :', array_keys($Data));
$Sth = $this->prepare("INSERT INTO $Table (`$FieldNames`) VALUES ($FieldValues)");
foreach ($Data as $Key => $Value) {
$Sth->bindValue(":$Key", $Value);
}
$Sth->execute();
}
public function Update($Table, $Data, $Where, $WhereBindArray = array()) {
ksort($Data);
$FieldDetails = null;
foreach ($data as $Key => $Value) {
$FieldDetails .= "`$Key`=:$Key,";
}
$FieldDetails = rtrim($FieldDetails, ',');
$Sth = $this->prepare("UPDATE $Table SET $FieldDetails WHERE $Where");
foreach ($Data as $Key => $Value) {
$Sth->bindValue(":$Key", $Value);
}
foreach ($WhereBindArray as $Key => $Value) {
$Sth->bindValue(":$Key", $Value);
}
$Sth->execute();
}
public function Delete($Table, $Where, $Bind = array(), $Limit = null) {
$Query = "DELETE FROM $Table WHERE $Where";
if ($Limit) {
$Query .= " LIMIT $Limit";
}
$Sth = $this->prepare($Query);
foreach ($Bind as $Key => $Value) {
$Sth->bindValue(":$Key", $Value);
}
$Sth->execute();
}
}
?>
Is there a logical explaination why it is showing uncaught PDO exception.
This is the error message i get.
this is what it outputs Fatal error: Uncaught PDOException: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\vendor\Link.php:8 Stack trace: #0 C:\xampp\htdocs\vendor\Link.php(8): PDO->__construct('mysql:host=loca...', 'root', '') #1 C:\xampp\htdocs\vendor\Global.php(33): App\Framework\Link->__construct('mysql', 'localhostz', 'test', 'root', '', 'utf8', '3306') #2 {main} Next PDOException: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\vendor\Link.php:8 Stack trace: #0 C:\xampp\htdocs\vendor\Link.php(8): PDO->__construct('mysql:host=loca...', 'root', '') #1 C:\xampp\htdocs\vendor\Global.php(33): App\Framework\Link->__construct('mysql', 'localhostz', 'test', 'root', '', 'utf8', '3306') #2 {main} thrown in C:\xampp\htdocs\vendor\Link.php on line 8
So i figured it out it was the use of the namespaces by changing Global.php to:
<?php
use App\Framework as Framework;
define('APP_VERSION', '1.0.0');
defined("START") ? null : define("START", microtime());
define('DEBUG', true);
if (DEBUG) {
error_reporting(E_ALL);
ini_set('display_errors', 1);
} else {
error_reporting(0);
ini_set('display_errors', 0);
}
include_once 'LinkConfig.php';
include_once 'LinkInterface.php';
include_once 'Link.php';
try {
$Link = new Framework\Link(
Framework\LinkConfig::DRIVER,
Framework\LinkConfig::HOST,
Framework\LinkConfig::DBNAME,
Framework\LinkConfig::USER,
Framework\LinkConfig::PASS,
Framework\LinkConfig::CHARSET,
Framework\LinkConfig::PORT
);
} catch (PDOException $Exception) {
echo 'Connection failed: ' . $Exception->getMessage();
}
?>
I'm trying to build a basic API with PHP and mysql and depending on the url path, different database tables are used and therefore the connection needs to be made. But I keep getting this error:
Fatal error: Call to a member function prepare() on a non-object
in....line 6
dashboard.class.php:
class dashboard {
public function getData($conn) {
// Get latest status
$stmt = $conn->prepare("SELECT status FROM status_archive ORDER BY datetime DESC LIMIT 1 ");
$stmt->execute(); //line 6
$stmt->bind_result($status);
$stmt->fetch();
($status == '1' ? $status = 'up' : $status = 'down');
$stmt->close();
return $status;
}
}
Function that creates the database connection:
function db_connection($type) {
$db = $type.'_db';
syslog(LOG_INFO, 'DB: '.$db);
// Check to see if a development or production server is being used
if (strpos(getenv('SERVER_SOFTWARE'), 'Development') === false) {
$conn = mysqli_connect(null,
getenv('PRODUCTION_DB_USERNAME'),
getenv('PRODUCTION_DB_PASSWORD'),
$db,
null,
getenv('PRODUCTION_CLOUD_SQL_INSTANCE'));
} else {
$conn = mysqli_connect(getenv('DEVELOPMENT_DB_HOST'),
getenv('DEVELOPMENT_DB_USERNAME'),
getenv('DEVELOPMENT_DB_PASSWORD'),
$db);
}
// Check if successful connection to database
if ($conn->connect_error) {
die("Could not connect to database: $conn->connect_error " .
"[$conn->connect_errno]");
}
return $conn;
}
This is the code at the end of the file that initiates everything:
$path_array = explode("/", parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH));
$conn = db_connection($path_array[3]);
include 'classes/dashboard.class.php';
$dashboard = new dashboard;
$results = $dashboard->getData($conn);
echo json_encode($results, JSON_PRETTY_PRINT);
mysqli_connect can to return falsy value.
You should use OOP style (new mysqli) or check $conn:
$conn = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if (!$conn) {
die('Connection error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
php.net - See "Procedural style" example.
It turned out it was due to variable scope.
I ended up using PHP $GLOBALS to get it to work.
I would like to make a CRUD class, for inserting, updating and deleting data, in the __contruct function, I don't want to call the connection, I would only specify the connection name, then I am getting this error:
PHP Fatal error: Call to a member function prepare
() on a non-object in crud.php on line 60
<?php
/* Start (config.php)
This part of code is only to show you that the connection name is "connexion" which is called in config.php
$connexion = new PDO('mysql:host='.$db_host.';dbname='.$db_name, $db_user, $db_passwd
, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES '.$db_charset.'')); //SET NAMES utf8
$connexion->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
EnD */
classDB.php
require_once('config.php');
final class crud {
public function __construct($connexionName) {
$this->connexionName = $connexionName;
}
public final function insert($tableName, $fields=array()){
$this->tableName = $tableName;
$this->fields = $fields;
foreach ($this->fields as $kf => $vf) {
$inKeys[] = $kf;
$inKeysDotted[] = ':' . $kf;
$insertedKeys = implode(', ', $inKeys);
$insertedKeysDotted = implode(', ', $inKeysDotted);
}
echo '<br />';
$sql = "INSERT INTO $this->tableName ($insertedKeys) VALUES ($insertedKeysDotted)";
$insertItems = $this->connexionName->prepare("$sql"); // THIS IS LINE 60
echo 'insert '.$insertItems.'<br />';
} // end insert()
} // end CRUD
$con = new crud($connexion);
echo '<br />';
$con->insert('ban_ip', array('visitor_type'=>'5', 'ip'=>'111.222.333.444'));
?>
Thanks in advance
Hi this is my php code:
<?php
function dbConnect() {
global $dbh;
$dbInfo['database_target'] = "localhost";
$dbInfo['database_name'] = "pdo";
$dbInfo['username'] = "root";
$dbInfo['password'] = "";
$dbConnString = "mysql:host=" . $dbInfo['database_target'] . "; dbname=" . $dbInfo['database_name'];
$dbh = new PDO($dbConnString, $dbInfo['username'], $dbInfo['password']);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$error = $dbh->errorInfo();
if($error[0] != "") {
print "<p>DATABASE CONNECTION ERROR:</p>";
print_r($error);
}
}
function dbQuery($queryString) {
global $dbh;
$query = $dbh->query($queryString);
$i = 0;
foreach ($query as $query2) {
$queryReturn[$i] = $query2;
$i++;
}
if($i > 1) {
return $queryReturn;
} else {
return $queryReturn[0];
}
}
dbConnect(); // Connect to Database
?>
when run this code, it shows output like this:
DATABASE CONNECTION ERROR:
Array ( [0] => 00000 [1] => [2] => )
I want to know, this code correct or not, and If any error in this code, please guide me, I am new to pdo.
Thank you.
Don't check errorInfo after making a connection.
PDO throws an exception if connection failed.
Please read the docs:
http://php.net/manual/en/pdo.query.php
http://en.php.net/PDOStatement
PDO::query returns a PDOStatement object. This class has a public property rowCount.
You don't need to iterate over all results, count em etc,..
ALL Code in function dbQuery($queryString) {
Can be replaced by a single line:
return $query->rowCount > 1 ? $query->fetch() : /* else */;
I think you meant global $dbInfo; instead of global $dbh; because dbInfo seems to be undefined in this function unlike dbh.
I need to get username, password etc from the wp-config file to connect to a custom PDO database.
Currently I have another file where I have this info, but I would like to only use the wp-config.
So how can I read the different properties of wp-config?
I have even defined my own constants in in wp-config.php and managed to retrieve them in theme without any includes.
wp-config.php
define('DEFAULT_ACCESS', 'employee');
functions.php
echo "DEFAULT_ACCESS :".DEFAULT_ACCESS;
outputs DEFAULT_ACCESS :employee
Here's some same code.
// ...Call the database connection settings
require( path to /wp-config.php );
// ...Connect to WP database
$dbc = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if ( !$dbc ) {
die( 'Not Connected: ' . mysql_error());
}
// Select the database
$db = mysql_select_db(DB_NAME);
if (!$db) {
echo "There is no database: " . $db;
}
// ...Formulate the query
$query = "
SELECT *
FROM `wp_posts`
WHERE `post_status` = 'publish'
AND `post_password` = ''
AND `post_type` = 'post'
";
// ...Perform the query
$result = mysql_query( $query );
// ...Check results of the query and terminate the script if invalid results
if ( !$result ) {
$message = '<p>Invalid query.</p>' . "\n";
$message .= '<p>Whole query: ' . $query ."</p> \n";
die ( $message );
}
// Init a variable for the number of rows of results
$num_rows = mysql_num_rows( $result );
// Print the number of posts
echo "$num_rows Posts";
// Free the resources associated with the result set
if ( $result ) {
mysql_free_result( $result );
mysql_close();
}
I would just include the file then I would have access to the variable in it varibales.
<?php
require_once('wp-config.php');
echo DB_NAME;
?>
This is assuming you're on the same server and you can access wp-config.php through the file system.
If you're doing this for a plugin, these values are already available. You won't need to include the file again.
You can get all the global constants from wp-config.php simply echo the const like that:
<?php
echo DB_HOST;
echo DB_NAME;
echo DB_USER;
echo DB_PASSWORD;
Here is a function to read all WP DB defines:
function get_wordpress_data() {
$content = #file_get_contents( '../wp-config.php' );
if( ! $content ) {
return false;
}
$params = [
'db_name' => "/define.+?'DB_NAME'.+?'(.*?)'.+/",
'db_user' => "/define.+?'DB_USER'.+?'(.*?)'.+/",
'db_password' => "/define.+?'DB_PASSWORD'.+?'(.*?)'.+/",
'db_host' => "/define.+?'DB_HOST'.+?'(.*?)'.+/",
'table_prefix' => "/\\\$table_prefix.+?'(.+?)'.+/",
];
$return = [];
foreach( $params as $key => $value ) {
$found = preg_match_all( $value, $content, $result );
if( $found ) {
$return[ $key ] = $result[ 1 ][ 0 ];
} else {
$return[ $key ] = false;
}
}
return $return;
}
this returns an array like this:
array (size=5)
'db_name' => string '.........'
'db_user' => string '.........'
'db_password' => string '.........'
'db_host' => string 'localhost'
'table_prefix' => string 'wp_'
If you want to connect to DB, for current versions of PHP, using mysqli extention is recommended (mysql extention is going to deprecate):
require_once ("../wp-config.php"); // path to wp-config depends on your file locatoin
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
Just add required wp-load.php file.
you can use all wordpress functionality like
get_recent_posts() and many more...