PHP webservice require file error - php

I'm trying to create a webservice with PHP and MySQL but I get errors when I try to require files. Here's my code:
db_config.php
<?php
define('DB_USER', "a1605031_test2");
define('DB_PASSWORD', "******");
define('DB_DATABASE', "a1605031_test2");
define('DB_SERVER', "mysql13.000webhost.com");
?>
DB_CONNECT.php
<?php
class DB_CONNECT {
function __construct() {
$this->connect();
}
function __destruct() {
$this->close();
}
function connect() {
require_once __DIR__ . '/db_config.php';
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
return $con;
}
function close() {
mysql_close();
}
}
?>
test.php
<?php
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
?>
But when I open test.php I get this
require_once() [function.require]:
Failed opening required '__DIR__/db_connect.php' (include_path='.:/usr/lib/php:/usr/local/lib/php')
in /home/a1605031/public_html/test2/test.php on line 2
So how should I require the file ? I'm using 000webhost.com, if it matters.

What version of PHP is installed? It looks like __DIR__ isn't defined - which was added in PHP 5.3. Try this instead:
require_once dirname(__FILE__) . '/db_connect.php';

Related

Unknown MySQL server host 'DB_HOST' (0)

I am trying to sent data to the server database, i implement it using wamp server it was working fine but when i installed the db on my domain and switched it to my domain its giving the following error.
I have kept my files inside a folder in root directory
Unknown MySQL server host 'DB_HOST' (0)
Below is my config file i am using to connect to the db
<?php
// Database configuration
define('DB_USERNAME', 'user');
define('DB_PASSWORD', 'xxxx');
define('DB_HOST', '192.210.195.245');
define('DB_NAME', 'tabanico_userlogin');
?>
here my code connecting db, config.php file contains the code pasted above
<?php
class DbConnect {
private $conn;
function __construct() {
// connecting to database
$this->connect();
}
function __destruct() {
$this->close();
}
function connect() {
include_once dirname(__FILE__) . './Config.php';
$this->conn = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME) or die(mysql_error());
// returing connection resource
return $this->conn;
}
// Close function
function close() {
// close db connection
mysql_close($this->conn);
}
}
?>
and my file receiving data
<?php
include_once './DbConnect.php';
function createNewPrediction() {
$response = array();
$id = $_POST["id"];
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$db = new DbConnect();
// mysql query
$query = "INSERT INTO login(id,name,email,password) VALUES('$id','$name','$email','$password')";
$result = mysql_query($query) or die(mysql_error());
if ($result) {
$response["error"] = false;
$response["message"] = "Prediction added successfully!";
} else {
$response["error"] = true;
$response["message"] = "Failed to add prediction!";
}
// echo json response
echo json_encode($response);
}
createNewPrediction();
?>
I have seen related post but didn't find useful answers. Can anyone help me in getting out of this. Thanks in advance.
Please post the code where you try to connect to the server. I guess you tried to connect using the following function:
mysql_connect('DB_HOST', 'DB_USERNAME', 'DB_PASSWORD');
Since you defined the host using define('DB_HOST', 'localhost');, you do not have to use apostrophes. DB_HOST is a constant here. So try to use to
mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);
instead. If you use apostrophes like in 'DB_HOST', it is interpreted as a string instead of the value of the constant DB_HOST containing localhost. That's a possible reason why you get the error that DB_HOST is an unknown host.
But please post the connection part of your code to see if that's really the mistake.

Echo data not being displayed

I am new to php development.I have created a database using phpmyadmin.Now i want all the data to be displayed on the page.But when ever i try to run the file nothing is showing up.I dont know why this is happening.
db_config.php
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "moviesreview"); // database name
define('DB_SERVER', "localhost"); // db server
$con = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
db_connect.php
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysqli_error($con));
// Selecing database
$db = mysqli_select_db($con,DB_DATABASE) or die(mysqli_error()) or die(mysqli_error($con));
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
Code
<?php
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
$con=new db_connect();
$strQuery="SELECT * FROM `moviesdetails WHERE `recent_upcoming` =0";
$result=mysqli_query($con,$strQuery);
while($row=mysqli_fetch_array($result)){
$row_array['movies_id']=$row['movies_id'];
$row_array['movies_name']=$row['movies_name'];
$row_array['movies_description']=$row['movies_description'];
$row_array['movies_time']=$row['movies_time'];
$row_array['movies_release_date']=$row['movies_release_date'];
$row_array['movies_youtube_link']=$row['movies_youtube_link'];
$row_array['recent_upcoming']=$row['recent_upcoming'];
$row_array['movies_image']=$row['movies_image'];
$row_array['movies_actors']=$row['movies_actors'];
array_push($response,$row_array);
}
echo json_encode($response);
?>
Error what i am getting
There are a few things wrong with your code.
The space between <? and php
A missing tick for your table, and a missing semi-colon for your query.
A missing DB connection link.
Your code:
<? php
^ space
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
$strQuery="SELECT * FROM `moviesdetails WHERE `recent_upcoming` =0"
^ ^
$result=mysqli_query($strQuery);
^ no DB connection
<?php
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
$strQuery="SELECT * FROM `moviesdetails` WHERE `recent_upcoming` =0";
$result=mysqli_query($con,$strQuery);
Using error reporting http://php.net/manual/en/function.error-reporting.php would have signaled that, including or die(mysqli_error($con)) to mysqli_query()
You've edited your question. You are mixing mysqli_ and mysql_ functions. They do not mix.
All mysql_error should be mysqli_error($con) and mysql_close() to mysqli_close($con)
Edit:
Replace the entire contents of db_connect.php with the following:
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "moviesdetails"); // database name
define('DB_SERVER', "localhost"); // db server
$con = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
Edit #2:
while($row=mysqli_fetch_array($result)){
$response[] = $row;
$row['movies_id'];
$row['movies_name'];
$row['movies_description'];
$row['movies_time'];
$row['movies_release_date'];
$row['movies_youtube_link'];
$row['recent_upcoming'];
$row['movies_image'];
$row['movies_actors'];
}
echo json_encode($response);
You have missing connection link as parameter in your mysqli_query() function. Should be:
$result = mysqli_query($connection_link, $strQuery);
http://php.net/manual/en/mysqli.query.php
$connection_link will have in this case following format:
// include db connect class
require_once __DIR__ . '/db_connect.php';
$connection_link = new DB_CONNECT();
But as #Fred -ii- said in comments, you have some syntax errors in PHP and SQL query too.
Your DB class is badly designed, you should store connection link in property and making queries through this class.

$db = new DB() confusion

Can any please explain what does it mean
$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
and it's giving me an Error
"Error: Could not load database file mysql!"
file contents
define('DB_DRIVER', 'mysql');
define('DB_HOSTNAME', 'localhost');
define('DB_USERNAME', 'XXX');
define('DB_PASSWORD', 'XXX');
define('DB_DATABASE', 'XXXX');
DB CLASS Constructor
public function __construct($driver, $hostname, $username, $password, $database) {
if (file_exists(DIR_DATABASE . $driver . '.php')) {
require_once(DIR_DATABASE . $driver . '.php');
} else {
exit('Error: Could not load database file ' . $driver . '!');
}
$this->driver = new $driver($hostname, $username, $password, $database);
}
You don't have driver for mysql database, check DIR_DATABASE folder for existence of the mysql.php file.
Assuming you're using OpenCart, have a look in your config.php file. Find a line that looks like the following:
define('DIR_DATABASE', '/something/something/system/database/');
Make sure the something/something is valid for your site. In particular, ensure the path points to a directory containing the mysql.php driver file. You'll probably find it doesn't, so you'll need to edit it so that it does.
You should also check that the Apache service user has privileges to access that file.

Can't use constants when trying to connect to database in the other file

I have a file called config.php in which i defined 4 constants:
<?php
define('HOST','localhost');
define('USER','root');
define('PASSWORD','');
define('DATABASE','some_database');
?>
What I want to do is call this script with request_once function inside the other php file called database.php which will use the constant from this file for connecting
<?php
require_once('config.php');
$connect = mysql_connect(HOST,USER,PASSWORD);
$select_db = mysql_select_db(DATABASE);
?>
What i get returned is that the host,user,password and database are not defined. Why is that? This is a sample simplified code i used for connection but the essence of the problem is here. Thank you in advance.
PHP by default DO NOT SHOW Notices of undefined constants. So if you use a undefined constant PHP would simple treat that one as a string. For example,
<?php
//define('__TEST__', 'foo');
print __TEST__; //Will print __TEST__ and raise E_NOTICE if it's enabled
if you uncomment above define() PHP will print foo instead and won't raise a notice.
Personally I would suggest you to make a bit deeper test:
0) Declare error_reporting(E_ALL) in config.php
1) Check whether file exists and it readable before you include this
2) Check whether constants are actually defined before you use them
Finally, It would like this:
File: config.php
<?php
error_reporting(E_ALL);
define('HOST','localhost');
define('USER','root');
define('PASSWORD','');
define('DATABASE','some_database');
File: dbconnection.php
<?php
//require() will produce FATAL error if inclusion fails, so we're OK
require_once('config.php');
if ( defined('HOST') && defined('USER') && defined('PASSWORD') && defined('DATABASE') ){
$connect = mysql_connect(HOST,USER,PASSWORD);
$select_db = mysql_select_db(DATABASE);
} else {
trigger_error('Some constants are missing', E_USER_ERROR);
}
you can try Include() just to see if it makes a difference. also if you are working on a local machine, you may want to use :
require_once(dirname(__FILE__) . "/config.php");
You should look into MYSQLI or PDO as the mysql functions are depreciated now:
define("DB_HOST", "");
define("DB_USERNAME", "");
define("DB_PASSWORD", "");
define("DB_NAME", "");
$Mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($Mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $Mysqli->connect_errno . ") " . $Mysqli->connect_error;
$Mysqli->close();
}

require_once doesn't work in PHP

If I try to open this simple file in my Browser:
<?php
require_once 'classes/settings.php';
class Mysql {
private $conn;
function __construct() {
$this->conn = new mysqli (DB_SERVER,DB_USER,DB_PASSWORD,DB_MEMBER) or die('There was a problem connecting to the database.');
if ($this->conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $this->conn->connect_errno . ") " . $this->conn->connect_error;
}
//echo $mysqli->host_info . "\n";
}
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT *
FROM users
WHERE username = ? AND password = ?
LIMIT 1";
if($stmt = $this->conn->prepare($query)) {
$stmt->bind_param('ss',$un,$pwd);
$stmt->execute();
if($stmt->fetch()) {
$stmt->close();
return true;
}
}
}
}
?>
I receive this warning error:
Warning: require_once(classes/settings.php): failed to open stream: No such file or
directory in /var/www/classes/Mysql.php on line 3 Fatal error: require_once(): Failed
opening required 'classes/settings.php' (include_path='.:/usr/share/php:/usr/share/pear')
in /var/www/classes/Mysql.php on line 3
I can't understand why, the file setting.php is in that folder, so what is the problem?
EDIT:
if I do the same this with another file for example this:
<?php
require_once 'classes/settings.php';
$host = "localhost";
$user = "root";
$pass = "pass";
$databaseName = "membership";
$tableName = "users";
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query("SELECT * FROM $tableName"); //query
$array = mysql_fetch_row($result); //fetch result
//--------------------------------------------------------------------------
// 3) echo result as json
//--------------------------------------------------------------------------
echo json_encode($array);
?>
In this way, it works without problem, I can't understand why the file and the path is right because in this second piece code all work.
Your script, var/www/classes/Mysql.php, is already in the classes directory. The file you're including is in the same directory. Remove the classes/ and use:
require_once 'settings.php';
Since you are with in the classes folder already you have two options
First option is to use a relative path
require_once 'settings.php';
Second option is to use an absolute path
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/settings.php'
Try to use $_SERVER['DOCUMENT_ROOT']
require_once ($_SERVER['DOCUMENT_ROOT'] . '/classes/settings.php');

Categories