Db not connecting -php - php

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>");

Related

Classes and methods with PDO, and retrieving the data

I'm new to OOP programming, and I'm really lost with this what the title says. When I try to put the query in a class and in another file, I get errors in a file called Main.php and don't even know what to do to fix them:
Notice: Undefined variable: sth in Select.php on line 10
Fatal error: Cannot access empty property in Select.php on line 10
If I put the select in Connection.php, it returns the rows just fine, but with classes, I get those.
Here's my code:
Connection.php:
<?php
$hostname = 'localhost';
$username = 'user';
$password = 'pass';
function connectDB ($hostname, $username, $password){
$dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
return $dbh;
}
$dbh = connectDB ($hostname, $username, $password);
echo 'Connected to database <br/>';
Select.php:
<?php require_once 'Connection.php';
class Select {
public function select() {
$sql= "select * from table limit 10; <br/>";
echo $sql;
$select = $dbh->query($sql)->fetchall(PDO::FETCH_ASSOC);
foreach($this->$sth as $row){
echo $row['column']."<br/>";
}
}
}
The question is, how can I print the result from the query (for example from main.php, which has an autoloader), and why do I get those errors, when on a single file, they work just fine?
Edit:
<?php
$test = new Select($dbh);
echo $test->select();
?>
Besides the fixes in the replies, I included Connection.php into the main.php, changed the echo in Select.php to return and it works perfectly now. Adding this in case someone ever gets as lost as me.
You do not want to iterate over the query, but the result of that query. So this probably is what you are looking for:
<?php
class Select {
public function select() {
$sql= 'select * from table limit 10';
$select = $dbh->query($sql)->fetchall(PDO::FETCH_ASSOC);
foreach($select as $row){
echo $row['column']."<br/>";
}
}
}
And you also need to take care that the $dbh object is actually present inside that method. Either inject it into the object or specify it as method argument. So your full class will probably look something like that:
<?php
class Select {
private $dbh;
public function __construct($dbh) {
$this->dbh = $dbh;
}
public function select() {
$sql= 'select * from table limit 10';
$select = $this->dbh->query($sql)->fetchall(PDO::FETCH_ASSOC);
foreach($select as $row){
echo $row['column']."<br/>";
}
}
}
And you instantiate the object like that:
$selectObj = new Select($dbh);
Some general warning, though: Using PDO's fetchall() method is convenient, but carries a huge risk: it means that the full result set has to be copied into an array inside the php script. For bigger results that may lead to issues with memory usage (scripts getting terminated for security reasons). Often it is the better approach to use a while loop over a single row fetched from the result set in each iteration.

Correct way of having multiple php functions to query a single (mysql) database

Working on a PHP website and I've encountered an efficiency issue that I can not solve on my own.
I have a couple of separate php files:
connection.php - connects to the database.
sqlFunctions.php - couple of functions that execute different sql (mysqli) queries, manipulate data and return it.
index.php - file that executes some of the functions from sqlFunctions.php and uses the returned values to display something in the page.
connection.php:
$servername = "DATA"; //Replaced to "DATA" for posting on stackoverflow
$username = "DATA";
$password = "DATA";
$dbname = "DATA";
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
sqlFunctions.php:
<?php
function query1(){
require('connection.php');
//PDO Query to DB, fetch, store, modify data etc.
mysqli_close($con);
//Return modified data
}
function query2(){
require('connection.php');
//PDO Query to DB, fetch, store, modify some other data etc.
mysqli_close($con);
//Return modified data
}
?>
index.php:
//Simplified version
require('sqlFunctions.php');
<?php echo query1();?>
So I was thinking - initiating a new connection to the db on every function call is not a good idea. And if I would initiate a connection to the db in a function in sqlFunctions.php - I would need to pass another variable/reference/pointer (you know what I mean) to every single function in that file and that is something that I don't want to do.
So what is the best approach to accomplish what I need?
TL;DR;:
Main file calls a function in a separate file
That function executes an sql query and returns data
Returned data is displayed
Without reopening/closing the db connection on every function call.
There are several options.
Option 1. Declare your database connection global inside each function.
sqlFunctions.php:
<?php
require('connection.php');
function query1(){
global $con;
// mysqli code with $con
}
function query2(){
global $con;
// mysqli code with $con
}
?>
Option 2. Use GLOBALS.
connection.php:
...
$GLOBALS['con'] = new mysqli($servername, $username, $password, $dbname);
...
sqlFunctions.php:
<?php
require('connection.php');
function query1(){
// mysqli code with $GLOBALS['con']
}
function query2(){
// mysqli code with $GLOBALS['con']
}
?>
Option 3. Wrap all functions into a class (note capital S).
SqlFunctions.php:
class SqlFunctions {
protected $con;
public function __construct() {
global $con;
// can also pass $con as parameter or init db here
$this->con = $con;
}
public function query1(){
// mysqli code with $this->con
}
public function query2(){
// mysqli code with $this->con
}
}
index.php:
require('SqlFunctions.php');
$sqlFunctions = new SqlFunctions();
<?php echo $sqlFunctions->query1();?>
In this case you can also initialize the connection right inside the class or pass it as a parameter to __construct().

How do I make $con available as a parameter of $Query?

I can get by with editing procedural PHP (just), but OOP is a different thing. So I'm not that experienced with what I'm doing here, but I'm trying my best...
I have a file called Quote.object.php containing the following:
$Query = new DbQuery( "INSERT", "quotes", $array );
$this->id = mysqli_insert_id();
mysqli_insert_id needs to be fed a DB connection parameter, but I'm not sure how to do it. There is another file called Mysql.handler.php containing the database connection variable - is there a way that I can make $con available as a parameter of $Query above?
class DbQuery extends DbConnectionInfo{
// file: includes/classes/MysqlQuery.php
// contains functions needed to perform queries on mysql database and functions for necessary data processing for application
// SELECT = new DbQuery("select", table,cols[$value] ,where[$col=$value],order[$value],limit);
// INSERT = new DbQuery("insert", table, data[$col=$value]);
// UPDATE = new DbQuery("update", table, data[$col=$value],where[$col=$value],limit);
// set testing as true for SQL reports in page
var $results;
var $sql;
function __construct($mode,$table = '',$var1 = '',$var2 = '',$var3 = '',$var4='')
//connects to database according to info in DbConnectInfo, runs query, closes connection
{
$temp = '';
$con = mysqli_connect($this->host, $this->user, $this->pass) or die ('There was a problem connecting to the database ' . (ENVIRONMENT == 'Development' ? mysqli_error() . "$this->user, $this->pass, $this->host" : ''));
mysqli_select_db($con,$this->db) or die ('There was a problem connecting to the database' . (ENVIRONMENT == 'Development' ? mysqli_error() : ''));
I'm trying to get $con from DbQuery so I can put it into mysqli_insert_id(). I assume that's what I need? Is there a way to get $con from DbQuery and put into mysqli_insert_id()? Or do you need more information to know this?
NB I've tried to be concise in trying to show just relevant information, apologies if I've missed other helpful info.
You're defining an object, so make $con a class variable, e.g.
function __construct() {
$this->con = mysqli_connect(...);
^^^^^^^----store in object
}
function foo() {
$result = mysqli_query($sql, $this->con);
^^^^^^^^---retrieve from object
}

DB connections. SQL retrieve error

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 !

Cant pass mysqli connection to class

I am trying to pass an mysqli database connection to a php class. The code I have so far (cut down for simplicity) is as follows:
db.php
$db_host = 'localhost';
$db_name = 'dbname';
$db_user = 'username';
$db_password = 'password';
$db = array('db_host'=>$db_host,
'db_name'=>$db_name,
'db_user'=>$db_user,
'db_password'=>$db_password);
$dbCon = new mysqli( $db['db_host'],
$db['db_user'],
$db['db_password'],
$db['db_name']);
if (mysqli_connect_errno())
{
die(mysqli_connect_error()); //There was an error. Print it out and die
}
index.php
<?php
require_once($_SERVER["DOCUMENT_ROOT"] . "/db.php");
$sql = "SELECT id FROM usr_clients";
$stmt = $dbCon->prepare( $sql );
if ($stmt)
{
$stmt->execute();
$stmt->bind_result($id);
while($stmt->fetch())
{
$cl = new Client($id, $dbCon);
$cl->doIt();
}
$stmt->close();
}
?>
client.php
<?php
Class Client
{
private $con;
public static $clientCount = 0;
public function __construct( $id, $con )
{
$this->con = $con;
$sql = "SELECT id FROM usr_clients WHERE id = $id";
$stmt = $this->con->prepare( $sql );
if ($stmt)
{
echo "it worked!";
}
else
{
echo "it failed";
}
}
}
?>
Now the index.php page successfully recognises the database connection declared in db.php, and returns a list of all clients. It then loops through each client, and creates a "client" object, passing it the database connection.
It is here that the problem seems to start. In the client class, the database connection is not recognised. I get multiple errors on the page saying "it failed". In the logs, there is a line about calling prepare() on a non object.
Can anyone explain why the connection works in index.php, but not in the client class?
Thanks
Your main problem is assumptions.
You are assuming that there is no connection passed, judging by indirect consequence.
But a programmer should be always logically correct in their reasoning.
Talking of connection? Verify the very connection. var_dump($con) in the constructor. var_dump($this->con) in the method. If it fails - only now you can blame connection and start for the solution.
If not - there is no reason in looking for another connection passing method. Yet it's time to find the real problem.
If your query fails, you have to ask mysql, what's going on, using $this->con->error, as this function will provide you with a lot more useful information than simple "it fails". The right usage I've explained here: https://stackoverflow.com/a/15447204/285587

Categories