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');
Related
I'm trying to connect to a database using a config file that is a part of my Joomla website.
My config file looks like:
<?php
class JConfig {
public $dbtype = 'mysqli';
public $host = 'localhost';
public $user = 'xxxx';
public $password = 'xxxx';
public $db = 'xxxx';
public $dbprefix = 'xxxx_';
}
Below is the page that includes the configuration file:
<?php
include("configuration.php");
// Create connection
$conn = mysqli_connect($host, $user, $password, $db);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, navn, email FROM XXXX";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// Output data of each row
while ($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["navn"]. " " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
However, I cannot connect to the database as I get the following error message:
Connection failed: Access denied for user ''#'localhost' (using password: NO)
I think the issue might be because the config file has public in front of all the variables.
Question: How can I get around keeping the variables public, since the Joomla script needs them, but avoid the error?
Assuming the path is correct, do this instead:
require_once "configuration.php";
$Conf = new JConfig;
// Create connection
$conn = mysqli_connect($Conf->host, $Conf->user, $Conf->password, $Conf->db);
In simple terms the config file contains an class named JConfig, so you must instantiate that class and access it's public properties.
other stuff
Use require not include, as this config is needed for the rest of this script to work and include will just ignore missing files. Require will produce an error, and let you know what is wrong when the file is missing/no found. Further, use require once because you cannot redefine the same class multiple times.
PS. you don't need the () on include/require, and the same is true for construct with no arguments... (I'm lazy so I don't like to type those things out)
Enjoy!
I am trying to start a pgsql connection in php but i get pg_last_error(): No PostgreSQL link opened yet Please forgive my amateur question as i am a bit new to php.
Here is my php code:
<?php
$connect = pg_connect("host=xxx.xx.xxx.21 dbname=d106 user=b16 password=bran") or die("Could not connect: " . pg_last_error());
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bikes");
if (!$result)
{
echo "no results ";
}
while($row = pg_fetch_array($result))
{
$coor = $row['thestartgeom'];
echo $coor;
}
pg_close($connect);
?>
In your pgsql connection you have missed the port number.
Try this way.
<?php
$host = "host=xxx.xx.xxx.21";
$port = "port=5432";
$dbname = "dbname=d106";
$credentials = "user=b16 password=bran";
$connect= pg_connect( "$host $port $dbname $credentials" ) or die("Could not connect: " . pg_last_error());
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bikes");
if (!$result)
{
echo "no results ";
}
while($row = pg_fetch_array($result))
{
$coor = $row['thestartgeom'];
echo $coor;
}
pg_close($connect);
?>
You can store PgSQL connection code in one PHP file to reuse
pgsql_db_connection.php file
<?php
$host = "host=xxx.xx.xxx.21";
$port = "port=5432";
$dbname = "dbname=d106";
$credentials = "user=b16 password=bran";
$connect= pg_connect( "$host $port $dbname $credentials" );
if(!$connect){
echo "Error : Unable to open database\n";
}
?>
Call pgsql_db_connection.php file in other php files to use your database connection.
<?php
require_once('pgsql_db_connection.php');
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bikes");
if (!$result)
{
echo pg_last_error($connect);
exit;
}
while($row = pg_fetch_array($result))
{
$coor = $row[0];
echo $coor;
}
?>
When pg_connect fails, it returns FALSE and produces a PHP warning with the detailed information on why it couldn't initiate the connection. If you can see the other message:pg_last_error(): No PostgreSQL link opened yet that you're reporting, I'd expect you should be able to see the previous one too, which is the one normally telling the reason of the failure.
If the display_errors configuration setting is set to 0, the first message would not show up on the browser/screen but the second would not either.
Anyway, assuming you can't have access to pg_connect warnings for whatever reason such as custom error handler, what's wrong with your code is that pg_last_error() must have an already opened connection to work.
To access the detailed error message from a failed pg_connect, the built-in PHP function error_get_last() (returning an array) could be used.
<?
$connect= pg_connect("your-connect-string");
if (!$connect) {
print_r(error_get_last());
// for only the message:
// echo error_get_last()['message']
}
die("DB connection failed");
?>
See also how to catch pg_connect() function error? if you prefer exceptions.
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.
Can any of you guys help me to reorganize this code? I'll try to explain the problem below.
I have a db_connection.php wich includes the following (just my db info and don't worry, i am just using it locally):
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=webappeind;charset=utf8','root','');
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
But the problem is i have the following file that also includes my db info, but i do not know how to reorganize my code to get it working with my separate php file.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webappeind";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM zoekopdrachten ORDER BY titel DESC LIMIT 3";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output gegevens van elke rij
while($row = $result->fetch_assoc()) {
echo "<div class='recenttoegevoegd'>"."<a href='#'>".$row["titel"]."</a>"."</div>";
}
} else {
echo "0 resultaten";
}
?>
You can put the connection information in a separate file called, say, conn.php where you mention the code related to database opening, including credentials. Then, in the calling file, say putdata.php, you use the "require" or "require_once" command to include that conn.php. Let the conn.php file return a connection. Somewhat like this :
<?php
function GetMyConn() {
$server_name = "localhost";
$db_name = "db_name_goes_here";
$db_user = "user_name_goes_here";
$db_pass = "password_goes_here_muahhhaa";
$db_full_addr = "mysql:host=" . $server_name . ";" . "dbname=" . $db_name;
$MyConn = new PDO($db_full_addr, $db_user, $db_pass);
$MyConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $MyConn;
}
?>
In the calling file, you would say, something like :
require_once "GetConn.php";
$MyConnHere = GetMyConn();
$SqlHere = "Sql Statemetn goes here...."
$SqlHere2 = $MyConnHere->prepare($SqlHere);
$SqlHere2->execute();
Also, I suggest you can download the source code of some open source PHP application, such as mantissa, and see how they have organized their code files, folders and settings.
I am using WebMatrix Beta 3 which has support for php 5.2 and 5.3 I am able to run php pages but when I am trying to connect to mySql DB its not working.
Can anyone please suggest me the right way of doing it.
The connection code is written in a file called dbinfo.php which resides under config folder
<?php
$hostname = '127.0.0.1';
$username = 'root';
$password = 'password';
$database = 'test';
$link = mysql_connect($hostname, $username, $password)
or die("Could not connect : " . mysql_error());
mysql_select_db($database) or die("Could not select database");
//Below function added to allow customized unescaping.
function mysql_unescape($sRet_VAL=""){
$sRet_VAL = str_replace('\"','"',$sRet_VAL);
$sRet_VAL = str_replace("\'","'",$sRet_VAL);
return $sRet_VAL;
}
?>
and I am using this file as follows
<?php
require_once( $_SERVER['DOCUMENT_ROOT'] . '/config/dbinfo.php');
?>
<?php
$query = "SELECT * from temp";
$result = mysql_query($query)
or die("Error: " . mysql_error());
?>
it worked seems like webmatrix do not recognize I replaced it wilt <>php echo $varData ?> and it worked.