PDO throw error Undefined variable: pdo in - php

I have 3 files: dbconnect (here's declaration of $pdo), core.php (file with class to manage) and test.php.
I want to receive data from DB, but I have error:
Notice: Undefined variable: pdo in C:\xampp\htdocs\project\core.php on line 24
In dbconnect $pdo is in try catch, but before this I put: $pdo=null(to make variable accessible) but it doesn't work.
dbconnect ---> core.php(error here) ---> test.php;
//dbconnect.php
<?php
$mysql_host = 'localhost';
$username = 'root';
$password = '';
$database = 'db';
$pdo = null;
try {
$pdo = new PDO('mysql:host='.$mysql_host.';dbname='.$database.';charset=utf8', $username, $password );
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone.<br />';
}
?>
//core.php
require_once('cms/dbconnect.php');
class getCore{
public $link_allegro;
public $link_facebook;
function getLinks(){
$query= $pdo->query('SELECT `url` FROM `links` WHERE `title` = "facebook"');
$row = $query->fetch();
$this->link_facebook = $row["url"];
$query= $pdo->query('SELECT url FROM links WHERE title = "allegro"');
$row = $query->fetch();
$this->link_allegro = $row["url"];
$query->closeCursor();
}
}
//test.php
<?php
require_once('core.php');
$tmp = new getCore;
$tmp->getLinks();
echo $tmp->link_allegro;
echo $tmp->link_facebook;
?>
Anyone can solve this? Thanks.

This is a scoping problem. $pdo doesn't exists in your getCore class.
You can make a DatabaseConnect class to manage your db access.
You can use this basic class for your database connection :
<?php
class DatabaseConnect {
private $mysql_host = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'db';
private $pdo = null;
public function getPdo(){
return $this->pdo;
}
public function __construct(){
try {
$this->pdo = new PDO('mysql:host='.$mysql_host.';dbname='.$database.';charset=utf8', $username, $password );
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone.<br />';
}
}
}
?>
You can getting your PDO instance in an other class with calling DatabaseConnect object -> getPdo() :
- Instannciate a new DatabaseConnect.
- Get PDO instance with the methof of the class.
Like that :
$databaseConnect = new DatabaseConnect();
$pdo = $databaseConnect->getPdo();
You next code :
//core.php
require_once('cms/dbconnect.php');
class getCore{
public $link_allegro;
public $link_facebook;
function getLinks(){
$databaseConnect = new DatabaseConnect();
$pdo = $databaseConnect-getPdo();
$query= $pdo->query('SELECT `url` FROM `links` WHERE `title` = "facebook"');
$row = $query->fetch();
$this->link_facebook = $row["url"];
$query= $pdo->query('SELECT url FROM links WHERE title = "allegro"');
$row = $query->fetch();
$this->link_allegro = $row["url"];
$query->closeCursor();
}
}
//test.php
<?php
require_once('core.php');
$tmp = new getCore;
$tmp->getLinks();
echo $tmp->link_allegro;
echo $tmp->link_facebook;

You need to pass $pdo to the getLinks() function as an input to make it available for use. you could try getLinks($pdo)

Related

Uncaught Error: Call to a member function prepare() (PDO, php)

I'm trying to get data from a table using a public function in PHP, but I get this error:
Uncaught Error: Call to a member function prepare() (PDO, php)
I'm searching for 2, 3 hours... But no result is similar or I did not understand.
<?php
class Config {
public static $SQL;
private function __construct() {
$host_name = "localhost";
$base_user = "root";
$base_pass = "";
$base_name = "home_page";
try {
self::$SQL = new PDO("mysql:host=$host_name;dbname=$base_name", $base_user, $base_pass);
self::$SQL->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
die("Something went wrong, database connection closed. Reason: ". $e->getMessage());
}
}
public static function GetData($table, $data, $id) {
$wc = Config::$SQL->prepare('SELECT `'.$data.'` FROM `'.$table.'` WHERE `ID` = ?');
$wc->execute(array($id));
$r_data = $wc->fetch();
return $r_data[$data];
}
}
?>
And I use this in my base file:
<h1><?php echo Config::GetData("page_details", "Moto", 1) ?></h1>
The error is from this line:
$wc = self::$SQL->prepare('SELECT `'.$data.'` FROM `'.$table.'` WHERE `ID` = ?');
Is there any particular reason why you want to use STATICeverywhere? The common approach is using public, dynamic methods and properties. I rewrote your sample with suggested naming convention in PHPs OOP, it works:
<?php
class Config
{
/** #var PDO $conn */
private $conn = null;
public function __construct()
{
$host_name = "localhost";
$base_user = "root";
$base_pass = "";
$base_name = "home_page";
try {
$this->conn = new PDO("mysql:host=$host_name;dbname=$base_name", $base_user, $base_pass);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully"; // <- this is unnnesesary
} catch (PDOException $e) {
die("Something went wrong, database connection closed. Reason: " . $e->getMessage());
}
}
public function findById($table, $data, $id)
{
$stmt = $this->conn->prepare('SELECT `' . $data . '` FROM `' . $table . '` WHERE `uid` = ?');
$stmt->execute(array($id));
return $stmt->fetch(PDO::FETCH_ASSOC);
}
}
// just for test
$cfg = new Config();
print_r($cfg->findById('foo', '*', 1));
or in your case
<?php echo $cfg->findById("page_details", "Moto", 1)['Moto'] ?>

Setting up a database connection class in PHP

I was recently introduced to the idea of classes in PHP, and after some research I've come to the conclusion that I need to store database related functions in a class to access later. It has worked for the most part, but some use cases I am still confused with. For example,
Below is an example of how I would normally connect to my database and display information from user id's in a table
dbcon.php:
<?php
$con = mysqli_connect("host","username","password","database") or die("Couldn't connect");
require_once("functions.php");
?>
functions.php
function getUserInfo($id) {
$query = mysqli_query($con, "SELECT * FROM users WHERE id = '$id'");
return mysqli_fetch_array($query);
}
Some random file:
require_once("dbcon.php");
$result = mysqli_query($con, "SELECT * FROM tablename");
while ($row = mysqli_fetch_assoc($result)) {
$userinfo = getUserInfo($row['userid']);
echo $userinfo['name'];
}
?>
I don't feel like this method of querying the database and displaying information is the neatest or most efficient way possible. I read this article about using classes to tamper with a database and call functions that I created in the class.
My first question is this: When I try to access $con in functions.php, it is undefined. How can I pass the variable from dbcon.php to functions.php over the require_once function?
I also would like to know what the best way to store my connection to the database is, and if there are any tutorials on how to set that up.
I hope you understood that lol.
You can do it like this way:-
Dbconnection.php:-
<?php
Class DbConnection{
function getdbconnect(){
$conn = mysqli_connect("host","username","password","database") or die("Couldn't connect");
return $conn;
}
}
?>
Function.php:-
<?php
require_once('Dbconnection.php');
Class WorkingExamples{
function getUserInfo($id) {
$Dbobj = new DbConnection();
$query = mysqli_query($Dbobj->getdbconnect(), "SELECT * FROM users WHERE id = '$id'");
return mysqli_fetch_array($query);
}
}
$data = new WorkingExamples();
echo "<pre/>";print_r($data->getUserInfo(3));
?>
Note:- this is an example, try it by changing values according to your requirement and get the result.
<?php
class DatabaseConnection
{
private $host = "127.0.0.1";
private $dbname = "online_english";
private $dbUsername = "root";
private $dbPass = "";
private $charset = 'utf8mb4';
private $dsn;
public function tryConnect(){
try{
$this->dsn = "mysql:host=$this->host;dbname=$this->dbname;charset=$this->charset";
$DBH = new PDO($this->dsn,$this->dbUsername,$this->dbPass);
$DBH->exec("set names utf8");
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $DBH;
}
catch (PDOException $e){
$e->getMessage();
}
}
}
?>
<?php
class Database{
const DB_HOSTNAME = 'localhost';
const DB_USERNAME = 'root';
const DB_PASSWORD = 'root';
const DB_NAME = 'stockganesha';
public $_db_connect;
protected $_sql;
protected $_result;
protected $_row;
function db_connect(){
$this->_db_connect = mysqli_connect(self::DB_HOSTNAME,self::DB_USERNAME,self::DB_PASSWORD,self::DB_NAME) or die(mysql_error());
return $this->_db_connect;
}
function sql(){
$this->_sql = 'SELECT * FROM customers';
}
function query(){
$this->_result = mysqli_query($this->_db_connect,$this->_sql);
}
function fetch_array(){
while($this->_row = mysqli_fetch_array($this->_result)){
$username = $this->_row['first_name'];
echo "<ul>";
echo "<li>".$username."</li>";
echo "</ul>";
}
}
function db_close(){
mysqli_close($this->_db_connect);
}
}
and Import this in another class
<?php
require_once('../Config/Dbconnection.php');
include './model.php';
class CustomerDTO{
private $mysql;
function __construct() {
$database = new Database();
$this->mysql = $database->db_connect();
}
function create($customer){
$firstName = $customer->getFirstName();
$lastName = $customer->getLastName();
$emailId = $customer->getEmailId();
$mobileNumber = $customer->getMobileNumber();
$dateOfBirth = $customer->getDateOfBirth();
$phoneNumber = $customer->getPhoneNumber();
$termAndCondtion = $customer->getTermAndCondition();
$result = mysqli_query($this->mysql, "Insert into customers (first_name,last_name,email_id,mobile_number,date_of_birth,phone_number,term_and_condition)
values('$firstName','$lastName','$emailId','$mobileNumber','$dateOfBirth','$phoneNumber','$termAndCondtion')");
return $result;
}
function read(){
$result = mysqli_query( $this->mysql, "Select * from customers");
return $result;
}
function update($id, $customer){
$result = mysqli_query($this->mysql, "update customers set
first_name = ".$customer->getFirstName()."
last_name = ".$customer->getLastName()."
email_id = ".$customer->getEmailId()."
mobile_number = ".$customer->getMobileNumber()."
date_of_birth = ".$customer->getDateOfBirth()."
phone_number = ".$customer->getPhoneNumber()."
term_and_condition = ".$customer->getTermAndCondition()."
where id = ".$customer->getId());
return $result;
}
public function delete($id){
$result = mysqli_query($this->mysql, "delete from customers where id =".$id);
return $result;
}
}

Connect to DB with PHP Class isn't working when try to retrieve results

Good morning.
I'm trying to make a DB class to connect and retrieve results from my DB. So, I think with the class is everything good. But, the results won't appear.
Here is my DB class:
<?php class Conexao {
var $host = "localhost";
var $usuario = "root";
var $senha = "xxxxxx";
var $banco = 'restaurante';
private $mysqli;
public function Abrir()
{
$this->mysqli = new mysqli($this->host, $this->usuario, $this->senha, $this->banco);
}
public function Fechar()
{
$this->mysqli->close();
}
}
class Comando {
public function Executar($sql)
{
$con = new Conexao();
$con->Abrir();
$re = $con->mysqli->query($sql);
$con->Fechar();
return $re;
}
}
?>
And here is where I'm trying to retrieve the results:
<?php
$queryMesasAtivas = Comando::Executar('SELECT * FROM mesas WHERE status =1 AND numero !="'.$_SESSION["mesa"].'"');
if ($queryMesasAtivas->num_rows > 0) {
while ($rowMesasAtivas = $queryMesasAtivas->fetch_assoc()) {
echo "<option value='".$rowMesasAtivas['numero']."'>Mesa ".$rowMesasAtivas['numero']."</option>";
}
}
else {
echo '<option>Nenhuma mesa ativa</option>';
}
?>
I tried some modifications but, nothing changes. Everytime it's still not working. What's wrong?
As the Comando::Executar is not static, but rather declared as public function..., you will have to do something such as:
$comando = new Comando();
$queryMesasAtivas = $comando->Executar('SELECT * FROM mesas WHERE status =1 AND numero !="'.$_SESSION["mesa"].'"');
if ($queryMesasAtivas->num_rows > 0) {
while ($rowMesasAtivas = $queryMesasAtivas->fetch_assoc()) {
echo "<option value='".$rowMesasAtivas['numero']."'>Mesa ".$rowMesasAtivas['numero']."</option>";
}
}
else {
echo '<option>Nenhuma mesa ativa</option>';
}
Or declare the method as static, namely:
public static function Executar($sql)
{
$con = new Conexao();
$con->Abrir();
$re = $con->mysqli->query($sql);
$con->Fechar();
return $re;
}
And then you can use the double colon (::) syntax:
$queryMesasAtivas = Comando::Executar('SELECT * FROM mesas WHERE status =1 AND numero !="'.$_SESSION["mesa"].'"');
I would suggest not calling an open and close every time you run a query, but rather a class like this:
class Conexao
{
private $link;
public function __construct($host = null, $username = null, $password = null, $dbName = null)
{
$this->link = mysqli_init();
$this->link->real_connect($host, $username, $password, $dbName) or die("Failed to connect");
}
public function __destruct()
{
$this->link->close();
}
public function Query($sql)
{
return $this->link->query($sql);
}
}
This is then used as such:
$conexao = new Conexao("host", "username", "password", "db_name");
$result = $conexao->Query("SELECT * FROM `table` WHERE 1 ORDER BY `id` ASC;");
This is not only smaller, but more lightweight on the server because you aren't permanently opening and closing database connections, reducing CPU use and memory use.
Using static properties for the host etc. (keeps them in memory even after __destruct is used so you do not need to redeclare them every time):
class Conexao
{
private $link;
private static $host, $username, $password, $dbName;
public function __construct($host = null, $username = null, $password = null, $dbName = null)
{
static::$host = $host ? $host : static::$host;
static::$username = $username ? $username : static::$username;
static::$password = $password ? $password : sattic::$password;
static::$dbName = $dbName : $dbName : static::$dbName;
$this->link = mysqli_init();
$this->link->real_connect(static::$host, static::$username, static::$password, static::$dbName) or die("Failed to connect");
}
public function __destruct()
{
$this->link->close();
}
public function Query($sql)
{
return $this->link->query($sql);
}
}
$conexao = new Conexao("host", "username", "password", "db_name");
$result = $conexao->Query("SELECT * FROM `table` WHERE 1 ORDER BY `id` ASC;");
$conexao->__destruct(); // Destroy the class
$conexao = new Conexao(); // Reinitialise it
$result = $conexao->Query("SELECT * FROM `table` WHERE 1 ORDER BY `id` ASC;");
Using a config instance of the connection class:
config.php file:
<?php
require_once 'path/to/Conexao.php';
$conexao = new Conexao("host", "username", "password", "db_name");
?>
index.php file:
<?php
require_once 'config.php';
$result = $conexao->Query("SELECT * FROM `table` WHERE 1 ORDER BY `id` ASC;");
?>
The class now has a parent on my github!

DB class wont load

I'm trying to connect using a simle db class. For some reason it only print out
"Initiate DB class"
test.php
include 'db.class.php';
echo 'Initiate DB class';
$db = new DB();
echo 'DB class did load';
db.class.php
class DB extends mysqli {
private static $instance = null;
private function __construct () {
parent::init();
$host = 'localhost';
$user = 'root';
$pass = 'MY_PASS';
$dbse = 'MY_DB';
parent::real_connect($host, $user, $pass, $dbse);
if (0 !== $this->connect_errno):
die('MySQL Error: '. mysqli_connect_error());
//throw new Exception('MySQL Error: '. mysqli_connect_error());
endif;
}
public function fetch ($sql, $id = null, $one = false) {
$retval = array();
if ($res = $this->query($sql)):
$index = 0;
while ($rs = $res->fetch_assoc()):
if ($one):
$retval = $rs; break;
else:
$retval[$id ? $rs[$id] : $index++] = $rs;
endif;
endwhile;
$res->close();
endif;
return $retval;
}
}
I have tried to search my log files for error but they come out empty.
Ok got it,
In your call to db your calling new DB(); which mean you're trying to call the constructor of your DB class.
In your DB class it looks like you're trying to create a singleton, but something is missing normally there would be something to assign the instance the database connection, and something that asks the instance if it's empty create a new connection or if it's not use the same instance.
At the end of the day to make this work you can change your constructor to public.
Try this:
Db_class:
class Db_class{
/***********************CONNECT TO DB*********************/
public function db_connect(){
$user = '***';
$db = '***';
$password = '***';
$host = '***';
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
return $dbh;
}
/******************PREPARE AND EXECUTE SQL STATEMENTS*****/
public function query($statement){
$keyword = substr(strtoupper($statement), 0, strpos($statement, " "));
$dbh = $this->db_connect();
if($dbh){
try{
$sql = $dbh->prepare($statement);
$exe = $sql->execute();
}
catch(PDOException $err){
return $err->getMessage();
}
switch($keyword){
case "SELECT":
$result = array();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
break;
default:
return $exe;
break;
}
}
else{
return false;
}
}
Other PHP:
$db = new Db_class();
$sql = "SQL STATEMENT";
$result = $db->query($sql);
Your constructor is marked as private which means new DB will raise an error. I see you have a private property to store an instance, are you missing the singleton method to return a new object?

could not find driver (php, PDO)

I find the error: could not find driver in the next script. I'm breaking my head over it now for some time now maybe you see the my fault.
This is my code:
class ConnectStation {
private $host = "localhost";
private $DatabaseType = "mysql";
private $database = array (
1 => "Database_one",
2 => "Database_two",
3 => "Database_true"
);
private $user1 = "MyUsername1";
private $pass1 = "MyPassword1";
private $user2 = "MyUsername2";
private $pass2 = "MyPassword2";
public function ConnectDB($user, $database){
if ($database==""){$database=1;}
try{
switch ($user){
case "ReadOnly":
$connection = new PDO("'".$this->DatabaseType.":host=".$this->host.";dbname=".$this->database[$database]."', '".$this->user1."', '".$this->pass1."'");
$connection->exec('SET CHARACTER SET utf8');
return $connection;
break;
case "Admin":
$connection = new PDO("'".$this->DatabaseType.":host=".$this->host.";dbname=".$this->database[$database]."', '".$this->user2."', '".$this->pass2."'");
$connection->exec('SET CHARACTER SET utf8');
return $connection;
break;
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
}
Oke so far the connection than the scrip i use for a query to send to the database. the code is like this:
$userCard = new ConnectStation;
$query = "SELECT username FROM users";
foreach ($this->ConnectDB('ReadOnly', 1)->query($query) as $row){
echo $row['username']."<br>";
}
Any help ore advise is welcome?
Your call to the PDO constructor is totally screwed up with unnecessary quotes and weird argument order. Just do:
$dsn = sprintf('%s:host=%s;dbname=%s', $this->DatabaseType, $this->host, $this->database[$database]);
$connection = new PDO($dsn, $this->user1, $this->pass1);

Categories