Notice and warning when using OOP php - php

<!---- Database File --->
<?php
require_once 'config.php';
class MySQLDatabase {
private $connection;
function __construct() {
$this->open_connection();
}
public function open_connection() {
$this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if(!$this->connection) {
die("Database connection Failed: " .mysqli_error($this->connection));
}else {
$db_select = mysqli_select_db($this->connection, DB_NAME);
if(!$db_select) {
die("Database connection Failed: " .mysqli_error($this->connection));
}
}
}
public function close_connection() {
if(isset($this->connection)) {
mysqli_close($this->connection);
unset($this->connection);
}
}
public function query($sql) {
$result = mysqli_query($sql, $this->connection);
$this->confirm_query($result);
return $result;
}
private function confirm_query($result) {
if(!$result) {
die("Database connection Failed: " .mysqli_error($this->connection));
}
}
}
$database = new MySQLDatabase();
$database->close_connection();
?>
<!----Config FIle which ---->
<?php
defined('DB_SERVER') ? null : define("DB_SERVER","localhost");
defined('DB_USER') ? null : define("DB_USER", "faizy");
defined('DB_PASS') ? null : define("DB_PASS", "faizy");
defined('DB_NAME') ? null : define("DB_NAME", "photo_gallery");
?>
<!---index.php---->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<?php
require_once '../includes/database.php';
if(isset($database)){ echo "true"; } else { echo "false"; }
echo "<h1>Working</h1>";
?>
</body>
</html>
Below are the warning and notice shown by my browser can anyone suggest why these are coming,When i use single php and try to connect that it connects,but when i use different function files and used OOP php than always these error are shown,Can anyone please help to solve these warnings and Notice
Notice: Use of undefined constant DB_SERVER - assumed 'DB_SERVER' in C:\xampp\htdocs\demo\oop\includes\database.php on line 13
Notice: Use of undefined constant DB_USER - assumed 'DB_USER' in C:\xampp\htdocs\demo\oop\includes\database.php on line 13
Notice: Use of undefined constant DB_PASS - assumed 'DB_PASS' in C:\xampp\htdocs\demo\oop\includes\database.php on line 13
Notice: Use of undefined constant DB_NAME - assumed 'DB_NAME' in C:\xampp\htdocs\demo\oop\includes\database.php on line 13
Warning: mysqli_connect(): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\demo\oop\includes\database.php on line 13
Warning: mysqli_connect(): (HY000/2002): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\demo\oop\includes\database.php on line 13
Warning: mysqli_error() expects parameter 1 to be mysqli, boolean given in C:\xampp\htdocs\demo\oop\includes\database.php on line 15
Database connection Failed:

I just made a test using all the above code in the three separate files and it all works for me. All I changed was the database name and pass to be one of my databases. You must be linking to the files wrong.

Put your constant definitions above the database logic and it'll work. That'll confirm that your require path is incorrectly configured.

Related

Trying to connect from iOS to MySQL Database using php ( HTTP POST )

Below is my sample code for my PHP program, and my database has already been created.
createteam.php:
<?php
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//getting values
$teamName = $_POST['name'];
$memberCount = $_POST['member'];
//including the db operation file
require_once '../includes/DbOperation.php';
$db = new DbOperation();
//inserting values
if($db->createTeam($teamName,$memberCount)){
$response['error']=false;
$response['message']='Team added successfully';
}else{
$response['error']=true;
$response['message']='Could not add team';
}
}else{
$response['error']=true;
$response['message']='You are not authorized';
}
echo json_encode($response);
config.php:
<?php
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_NAME', 'iphone');
DbConnect.php:
<?php
class DbConnect
{
private $conn;
function __construct()
{
}
/**
* Establishing database connection
* #return database connection handler
*/
function connect()
{
require_once 'Config.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// returing connection resource
return $this->conn;
}
}
DbOperation.php:
<?php
class DbOperation
{
private $conn;
function __construct()
{
require_once dirname(__FILE__) . '/Config.php';
require_once dirname(__FILE__) . '/DbConnect.php';
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
//Function to create a new user
public function createTeam($name, $memberCount)
{
$stmt = $this->conn->prepare("INSERT INTO team(name, member) values(?, ?)");
$stmt->bind_param("si", $name, $memberCount);
$result = $stmt->execute();
$stmt->close();
if ($result) {
return true;
} else {
return false;
}
}
}
However when I use HTTP POST method using Postman in Chrome, it states this
Notice: Undefined index: name in D:\xampp\htdocs\TestServ\api\createteam.php on line 9
Notice: Undefined index: member in D:\xampp\htdocs\TestServ\api\createteam.php on line 10
Warning: mysqli::__construct(): (HY000/1049): Unknown database 'iphone' in D:\xampp\htdocs\TestServ\includes\DbConnect.php on line 20
Failed to connect to MySQL: Unknown database 'iphone'
Warning: mysqli::prepare(): Couldn't fetch mysqli in D:\xampp\htdocs\TestServ\includes\DbOperation.php on line 20
Fatal error: Uncaught Error: Call to a member function bind_param() on null in D:\xampp\htdocs\TestServ\includes\DbOperation.php:21 Stack trace: #0 D:\xampp\htdocs\TestServ\api\createteam.php(18): DbOperation->createTeam(NULL, NULL) #1 {main} thrown in D:\xampp\htdocs\TestServ\includes\DbOperation.php on line 21
What does this mean, and what should I change?
Your first two errors are caused because of these two lines:
$teamName = $_POST['name'];
$memberCount = $_POST['member'];
The error (Undefined index) tells you that you have some non-existing variables, in this case name and member from your $_POST[] variable. Make sure your POST request is correctly made, see undefined variable for more information.
Your third error (Warning: mysqli::__construct(): (HY000/1049)) is caused because there isn't a database called iphone in your database system. Check if you have typed it correctly or if you haven't yet created an actual database with the name iphone.
The last error is caused because of the first two errors, since name and member aren't (correctly) defined in your POST request they have been set to NULL and the mysqli library doesn't like that.

Oops connection fails when called on 2nd instance

I have the following , relatively simple connection script to a database :
The below script is just creating a generic interface :
<?php
//Filename: IConnectInfo.php
interface IConnectInfo
{
const HOST ="localhost";
const UNAME ="root";
const PW ="";
const DBNAME = "login";
public static function doConnect();
}
?>
The script below, that makes use of the above interface:
<?php
//FILENAME :: UniversalConnect.php
ini_set("display_errors","1");
ERROR_REPORTING( E_ALL | E_STRICT );
include_once('IConnectInfo.php');
class UniversalConnect implements IConnectInfo
{
private static $server=IConnectInfo::HOST;
private static $currentDB= IConnectInfo::DBNAME;
private static $user= IConnectInfo::UNAME;
private static $pass= IConnectInfo::PW;
private static $hookup;
public static function doConnect()
{
self::$hookup=mysqli_connect(self::$server, self::$user, self::$pass, self::$currentDB);
if(self::$hookup)
{
echo "Successful connection to MySQL:<br/>";
}
elseif (mysqli_connect_error(self::$hookup))
{
echo('Here is why it failed: ' . mysqli_connect_error());
}
return self::$hookup;
}
}
?>
Now till here everything is neat and clean and works fine :
I tested the above two files are working , by adding the following 2 lines at the end of the above file .
$instance = new UniversalConnect();
$instance::doConnect();
I get a message "Successful connection to MySQL:" , perfect !!!
now comes the 3rd file : (I have commented out some of the code to make things simple) :
<?php
//FILENAME DataEntry.php
require_once('tablework/UniversalConnect.php');
class DataEntry
{
//Variable for MySql connection
private $hookup;
private $sql;
private $tableMaster;
//Field Variables
private $name;
private $email;
private $lang;
public function __construct()
{
//Get table name and make connection
$this->tableMaster="basics";
if($this->hookup=UniversalConnect::doConnect()){
echo "<b>connected</b>";
}else{
echo "<b>Not connected</b>";
}
}
}
$instance = new DataEntry();
?>
Now when i run the above file , somehow the connection to the database fails ! even though in UniversalConnect.php the connection is successful !
The error i get is
Here is why it failed: php_network_getaddresses: getaddrinfo failed:
No such host is known. Not connected.
I really don't understand why when the connection is made in UniversalConnect.php and the same connection is being returned to dataEntry.php , does the connection Fail ! .
EDIT :: List of errors :
Warning: mysqli_connect(): php_network_getaddresses: getaddrinfo
failed: No such host is known. in
C:\xampp\htdocs\Login2.0\tablework\UniversalConnect.php on line 19
Warning: mysqli_connect(): (HY000/2002): php_network_getaddresses:
getaddrinfo failed: No such host is known. in
C:\xampp\htdocs\Login2.0\tablework\UniversalConnect.php on line 19
Here is why it failed: php_network_getaddresses: getaddrinfo failed:
No such host is known. Warning: mysqli_connect():
php_network_getaddresses: getaddrinfo failed: No such host is known.
in C:\xampp\htdocs\Login2.0\tablework\UniversalConnect.php on line 19
Warning: mysqli_connect(): (HY000/2002): php_network_getaddresses:
getaddrinfo failed: No such host is known. in
C:\xampp\htdocs\Login2.0\tablework\UniversalConnect.php on line 19
Here is why it failed: php_network_getaddresses: getaddrinfo failed:
No such host is known. Not connected.
I would appreciate any help .
Thank you .
Tenali .

trouble with constants and connecting to database PHP

I'm getting these errors in my on screen
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(): 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(): 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.
Here is my code:
<?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());
}
}
}
My constants are defined as so:
<?php
// Database Constants
defined('DB_SERVER') ? null : define("DB_SERVER", "localhost");
defined('DB_USER') ? null : define("DB_USER", "gallery");
defined('DB_PASS') ? null : define("DB_PASS", "phpOTL123");
defined('DB_NAME') ? null : define("DB_NAME", "photo_gallery");
?>
What am I doing wrong?
I got the same errors and a small edit fixed it. By the way you should migrate to mysqli instead of mysql.
Here is my question : PHP constant not defined
You should replace the require_once in the database.php with the following code
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "config.php");
It will set the path to absolute and will work smoothly and fine
it seems that constants are not getting available to the mysql_connection function. Include the script in which constants are defined or define the constants in class MySQLDatabase itself.

Why do I still need to declare require_once('../config.php') in index.php? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have database.php that already has require_once('../config.php') inside it.
I don't understand why I still need to put both require_once('../config.php') and require_once('../database.php') in my index.php instead of require_once('../database.php') only since require_once('../config.php') is already inside database.php?
If I remove require_once('../config.php') in the index.php I am getting error.
<pre>Notice: Use of undefined constant DB_SERVER - assumed 'DB_SERVER' in C:\xampp\htdocs\lyndaphoto\includes\database.php on line 18
Notice: Use of undefined constant DB_USER - assumed 'DB_USER' in C:\xampp\htdocs\lyndaphoto\includes\database.php on line 18
Notice: Use of undefined constant DB_PASS - assumed 'DB_PASS' in C:\xampp\htdocs\lyndaphoto\includes\database.php on line 18
Warning: mysql_connect() [function.mysql-connect]: php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\lyndaphoto\includes\database.php on line 18
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\lyndaphoto\includes\database.php on line 18
Warning: mysql_connect() [function.mysql-connect]: php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\lyndaphoto\includes\database.php on line 18</pre>
config.php
$server = "localhost";
$user = "root";
$db_pass = "password";
$db_name = "photo_gallery";
define("DB_SERVER", $server);
define("DB_USER", $user);
define("DB_PASS", $db_pass);
define("DB_NAME", $db_name);
database.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);
}
}
}
$database = new MySQLDatabase();
$db =& $database;
both files are on "localhost/photogallery/includes/"
Thanks in advance! :)
All includes in your code are based on index.php (or running script), so require_once("config.php") will search the file on same dir of index.php. Try the following on database.php:
require_once(dirname(__FILE__) . "/config.php");
An alternative way to handle your include files is to make a single file called includes.php. It would contain all of your other resources.
// Filename: includes.php
require_once 'database.php';
require_once 'config.php';
Then, in your index.php and other documents you can access all of your application's resources by including that includes file.
require_once 'includes.php';

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