I define all my connections on an external file called db_config.php
This enables my class files to use db_config.php file for connections.
However, I am wondering if someone could shed some light on the following error.
SQL Retrieve Error: No database selected
This is referring to this line of code on db_config.php.
return array("host"=>"x", "username"=>"x", "password"=>"x", "dbname"=>"x" );
This is the function that makes the call
function openDB() {
$config = include_once("assets/configs/db_config.php");
$conn = mysqli_connect(
$config["host"] , $config["username"],
$config["password"], $config["dbname"]);
$this->conn = $conn;
return true;
}
What am I missing?
First of all make sure the variables in the config file are correct. If they are correct the try changing the include_once to include.
if that is not working, then change the code to :
function openDB() {
$config = array("host"=>"x", "username"=>"x", "password"=>"x", "dbname"=>"x" );
$conn = mysqli_connect(
$config["host"] , $config["username"],
$config["password"], $config["dbname"]);
$this->conn = $conn;
return true;
}
See if this works my way. If it does then your won't need the db.php file.
Please dump the $config variable and check what is going wrong ,
<?php
var_dump($config);
?>
So you can find $config is returning an array or not !
Related
I'm trying to include a variable from a different file into my main php file but I keep getting Undefined variable.
accounts.php
# GUEST CREDENTIALS
$host = 'localhost';
$guestAccount = 'oncofinder';
$guestPassword = 'xxxxxx';
$database = 'oncofinder';
#LOGGER CREDENTIALS
$loggerAccount = 'logger';
$loggerPassword = 'xxxxx';
connections.php
function guestConnection() {
try {
require 'accounts.php';
$conn = new PDO("pgsql:host=$host;dbname=$database", $guestAccount, $guestPassword);
} catch (PDOException $e) {
echo "Error : " . $e->getMessage() . "<br/>";
die();
}
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
I tried to put my require in and out of my function but nothing works. I really thought this was straightfoward but I can't find an obvious solution.
Is there any thing I'm doing wrong? Isn't this the procedure?
Regards
I think you have variables defined in global scope but you try to use it in local scope.
To confirm naming scope issue try to:
require 'accounts.php';
function guestConnection() {
global $host, $database, $guestAccount, $guestPassword;
try {
$conn = new PDO("pgsql:host=$host;dbname=$database", $guestAccount, $guestPassword);
...
This should work if your guestConnection() is in global scope not under any namespace or class.
or do move require out of try to get errors if any (file does not exist?):
function guestConnection() {
require('accounts.php');
try {
$conn = new PDO("pgsql:host=$host;dbname=$database", $guestAccount, $guestPassword);
...
I had a similar problem on my CentOS server. Try using the full absolute path (server conf might not be configured to allow calling of same-level files this way):
require_once $_SERVER['DOCUMENT_ROOT']. '/path/to/accounts.php';
Note:
you can use require and it should still work. I just think require_once is safer (in terms of not accidentally duping code).
I am trying to fetch table categories data from DB named stores. Here when I run this code it displays the DB error mentioned ie. Could not select the indicated database. How to resolve it? My DB name is correct plus $con variable is also not accessed in index.php while calling the function. Why is it so?
Note: The class code was in MySQL which is now depreciated. I have tried to convert it into MySQL.
index.php
require_once("ajax_table.class.php");
$obj = new ajax_table();
$records = $obj->getRecords($conn);
config.php
define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'root' );
define ( 'DB_PASSWORD', '' );
define ( 'DB_DB', 'stores' );
ajax_table.class.php
class ajax_table {
private $conn;
public function __construct(){
$this->$conn=$this->dbconnect();
}
private function dbconnect() {
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD,DB_DB)
or die ("<div style='color:red;'><h3>Could not connect to MySQL server</h3></div>");
return $conn;
}
function getRecords($conn){
$this->res = mysqli_query($conn,"select * from categories");
if(mysqli_num_rows($this->res)){
while($this->row = mysqli_fetch_assoc($this->res)){
$record = array_map('stripslashes', $this->row);
$this->records[] = $record;
}
return $this->records;
}
//else echo "No records found";
}
I cant see that you have included your config page into your database class?
Add this to your database class:
<?php require_once("config.php"); ?>
It looks like you have the parameters to mysqli_select_db switched. Check out this link which has the syntax and also suggests using the 4th parameter to mysqli_connect to select the database instead. As Rishi's answer noted, you're actually already doing that, so you can remove this call entirely!
Regarding the $conn variable, you are returning $conn from dbconnect, but not doing anything with it. You probably want to have a property on the class:
private $conn;
Then in dbconnect do something like:
$this->conn = $this->dbconnect();
And use $this->conn in getRecords instead of a parameter.
There are several ways you can solve this; the fundamental point is that you need the return from dbconnect to be kept somewhere and made available when you need to talk to the DB.
No need to use mysqli_select_db as you already selecting database in mysqli_connect.
Remove below line from your code
mysqli_select_db(DB_DB,$conn)
or die ("<div style='color:red;'><h3>Could not select the indicated database</h3></div>");
I am not very experienced in php oop. Moreover, when mysqli comes with php oop, it make me more confused about using it in best efficient way. Anyway, first look at my connection class:
<?php
//connectionclass.php
class connection{
public $conn;
public $warn;
public $err;
function __construct(){
$this->connect();
}
private function connect(){
$this->conn = # new mysqli('localhost', 'sever_user', 'user_password');
if ($this->conn->connect_error) {
$this->conn = FALSE;
$this->warn = '<br />Failed to connect database! Please try again later';
}
}
public function get_data($qry){
$result = $this->conn->query($qry);
if($result->num_rows>=1){
return $result;
}else{
$this->err = $this->conn->error;
return FALSE;
}
$result->free();
}
public function post_data($qry){
$this->conn->query($qry);
if($this->conn->affected_rows>=1){
return TRUE;
}else{
$this->err = $this->conn->error;
return FALSE;
}
}
}
?>
Now please structure of a php page which uses mysql database to store and get data:
<?php
//login.php
include('/include/connectionclass.php');
$db = new connection();
$query = "SELECT * FROM USERS WHERE user_country='India'";
$data = $db->get_data($query);
if($data){
while($row=$data->fetch_assoc()){
echo 'User Name: ':.$row["user_name"].' Age: '.$row["age"];
}
}
?>
So my login.php uses connection class to get data about users. All the things are running well. But one things made me confused. In connectionclass.php $this->conn is itself an object as it calls new mysqli. So this is an object inside another object $db. Moreover, When I am using $data = $db->get_data($query);, a result set is created inside object $db by method get_data, then this result set is copied into a variable $data inside login.php page.
So according to me, actually two result sets/data sets are creating here, one inside db object and one inside login page. Is it right way to use mysqli and php to get dataset from mysql database? Will it use more memory and server resources when the dataset is larger (when have to get large amount of data for many users)?
If it is not right way, please explain your points and please give me code which can be used efficiently for php oop and mysqli.
I've seen a few people with this same issue, yet none of the answers solved my problem. This is what I have in three files:
index.php:
$dbconnect = connectDB("mydb","connect");
mysqli_query($dbconnect,"INSERT INTO `mytable` (field1,field2) values ('value 1','value 2')");
connectDB("","kill",$dbconnect);
functions.php
function connectDB($db_name,$connectorkill,$link) { include('connectDB.inc.php'); }
connectDB.inc.php
$host="localhost";
$user="myusername";
$pass="mypassword";
if($connectorkill == "connect") {
if($dblink = mysqli_connect($host, $user, $pass, $db_name)) {
echo "dblink created.";
return $dblink;
} else { echo "Error connecting to database."; }
} elseif($connectorkill == "kill") { mysqli_close($link); }
and what I get is:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/username/public_html/members/index.php on line 2
which looks like the connectDB function is not doing its job, specifically the return of the $dblink variable in connectDB.inc.php. I went ahead and moved the code from connectDB.inc.php to inside the functions.php and it solved the problem, but I don't want it set up that way. Is there a way to solve this error?
Two solutions:
Solution 1: Refractor your code, something along the lines of:
config.php:
$config = array(
"databases" => array(
"my_database" => array(
"host" => "localhost",
"user" => "myusername",
"pass" => "mypassword"
)
)
);
functions.php:
require("config.php");
function connectDB($dbname)
{
global $config;
if (!isset($config["databases"][$dbname]))
return; // error, database info not in $config
$dbc = $config["databases"][$dbname];
$dbcon = mysqli_connect($dbc["host"], $dbc["user"], $dbc["pass"], $dbname);
if (!$dbcon)
return; // unable to connect error goes here
return $dbcon;
}
Note that this is just the bare minimum of a connectDB function. There really should be more error checking in there (for example, on each of the $dbc keys. It also needs proper error reporting and such, this is just a general hint in the right direction.
Solution 2: Add return in front of your include...
function connectDB($db_name,$connectorkill,$link) { return include('connectDB.inc.php'); }
Regardless of the solution: You really need some error checking code in your index.php because no matter what you do: Your connectDB function isn't always going to return a valid database connection.
I am having a strange error while creating objects. While I create an objects in chronological orders as classed defined, it is going on good. But when I change the order or object creation, it gives error.
The classes I am using are as follows:
<?php
class dbClass{
private $dbHost, $dbUser, $dbPass, $dbName, $connection;
function __construct(){
require_once("system/configuration.php");
$this->dbHost = $database_host;
$this->dbUser = $database_username;
$this->dbPass = $database_password;
$this->dbName = $database_name;
}
function __destruct(){
if(!$this->connection){
} else{
mysql_close($this->connection);
}
}
function mysqlConnect(){
$this->connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die("MySQL connection failed!");
mysql_select_db($this->dbName,$this->connection);
}
function mysqlClose(){
if(!$this->connection){
} else{
mysql_close($this->connection);
}
}
}
class siteInfo{
private $wTitle, $wName, $wUrl;
function __construct(){
require_once("system/configuration.php");
$this->wTitle = $website_title;
$this->wName = $website_name;
$this->wUrl = $website_url;
}
function __destruct(){
}
function showInfo($keyword){
if($keyword=="wTitle"){
return $this->wTitle;
}
if($keyword=="wName"){
return $this->wName;
}
if($keyword=="wUrl"){
return $this->wUrl;
}
}
}
?>
The problem is when I create objects in the following order, it is working perfectly:
include("system/systemClass.php");
$dbConnection = new dbClass();
$dbConnection -> mysqlConnect();
$siteInfo = new siteInfo();
But if I change the order to following
include("system/systemClass.php");
$siteInfo = new siteInfo();
$dbConnection = new dbClass();
$dbConnection -> mysqlConnect();
It gives error!
Warning: mysql_connect() [function.mysql-connect]: Access denied for user '#####'#'localhost' (using password: NO) in /home/#####/public_html/#####/system/systemClass.php on line 19
MySQL connection failed!
Your problem comes from the unconventional use of a configuration file that is read ONCE, but should be used in all classes.
When you instantiate the dbclass first, the configuration is read, probably variables get assigned, and you use these in the constructor.
After that, instantiating siteinfo will not read that file again, which is less harmful, because you only end up with an empty object that does return a lot of null, but does work.
The other way round, you get a siteinfo object with all the info, but a nonworking dbclass.
My advice: Don't use a configuration file that way.
First step: Remove the require_once - you need that file to be read multiple times.
Second step: Don't read the file in the constructor. Add one or more parameters to the constructor function and pass the values you want to be used from the outside.
Info: You can use PHP code files that configure stuff, but you shouldn't define variables in them that get used outside. This will work equally well:
// configuration.php
return array(
'database_host' => "127.0.0.1",
'database_user' => "root",
// ...
);
// using it:
$config = require('configuration.php'); // the variable now has the returned array