Correct use of PDO procedure not using global - php

I am having a play around with PDO and currently have the following code but I am getting Call to a member function prepare() on a non-object and I don't want to use global.
Do I use a class or do I pass it as a variable?
Config.php
function connection()
{
try
{
$host = 'localhost';
$dbuser = '';
$dbpass = '';
$dbname = '';
$dbConnection = new PDO("mysql:host=" . $host . ";dbname=" . $dbname.";", $dbuser, $dbpass);
return $dbConnection;
} catch (PDOException $error)
{
echo $error->getMessage();
return FALSE;
}
}
Functions.php
<?php
include('config.php');
$db = connection();
function listCars()
{
$query = $db->prepare("SELECT `id` `rego` `engineSize` `type` `colour` `year` `additionalFeatures` FROM `cars`");
$result = $query->fetchAll();
return $result;
}
?>
Index.php
<?php
include('assets/misc/functions.php');
var_dump(listcars());
?>

You have to load the db variable into your function, in Functions.php, look at this:
Functions.php
include('config.php');
$db = connection();
function listCars($db){
$query = $db->prepare("SELECT `id` `rego` `engineSize` `type` `colour` `year` `additionalFeatures` FROM `cars`");
$result = $query->fetchAll();
return $result;
}
?>
Index.php
<?php
include('assets/misc/functions.php');
var_dump(listcars($db));
?>
However, if you're looking for a more OOP approach, try the following:
<?php
class Cars {
protected $db;
public function __construct(PDO $db){
$this->db = $db;
}
public function listCars(){
$query = $this->db->prepare("... query ...")->execute();
return $query->fetchAll();
}
}
include('config.php');
$cars = new Cars(connection());
try {
var_dump($cars->listCars());
} catch (PDOException $e) {
echo $e;
}
?>

Related

How to fetch data from a MS-SQL Server Database using PHP?

I'm trying to fetch data from a SQL Server database. After debugging, I could figure there's something wrong with the function.
Here's the code:
db.php
class Db{
public static function getConnection() {
$server='xxx';
$database='xxx';
$user='xxx';
$password='xxx';
$dsn="dblib:host=" . $server . ";dbname=" . $database;
try {
$conn = new PDO($dsn, $user, $password);
}
catch (PDOException $e) {
echo 'SQL SERVER CONNECTION ERROR: ' . $e->getMessage();
}
return $conn;
}
}
functions.php
class Functions {
function getAcademicYear() {
$db = new Db();
$conn = $db->getConnection();
$conn->beginTransaction();
$sql = "SELECT academicYear FROM AcademicYear ORDER BY academicYearId DESC LIMIT 5";
$stmt = $conn->prepare($sql);
if ($stmt->execute()) {
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$conn->commit();
echo $result;
} else {
$conn->rollback();
echo "false";
}
}
}
The function is returning false. Can you please review it and point out any mistakes?

Connection is not defined

I have the following code
<?php
$host = "localhost";
$dbname = "hawkI";
$user = "root";
$password = "";
$userExist = false;
$userIP = null;
$userHasFinish = null;
$userLastPage = null;
try {
$dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
function getIPforBDD(){
return $_SERVER['REMOTE_ADDR'];
}
function UpdateUserProfile()
{
$requete = "SELECT * FROM users WHERE ip = ".getIPforBDD();
$result = $dbh->query($requete);
if($resultat->rowCount() == 0)
exit();
foreach($result as $ligne)
{
$userIP = $ligne['ip'];
$userhasFinish = $ligne['finish'];
$userLastPage = $ligne['lastPage'];
}
}
function CheckUserPosition()
{
UpdateUserProfile();
if(!$userExist)
AddUser();
return GetUserStatus();
}
function GetUserStatus()
{
$page;
if($userHasFinish)
$page = "end.php";
else
$page = $userLastPage;
return $page;
}
function AddUser()
{
$requete = "INSERT INTO users (ip, finish, lastPage) VALUES (".getIPforBDD().", ".false.", questionnaire_initial.php)";
$result = $dbh->query($requete);
}
function SavePageInBDD($page){
$requete = "UPDATE users SET lastPage = '.$page.' WHERE ip = ".getIPforBDD();
$result = $dbh->query($requete);
}
?>
But, I have a problem when I use it
( ! ) Notice: Undefined variable: dbh in C:\wamp64\www\HawkI\bdd.php
on line 66
I do not understand correctly how PHP work it's the first time I use it, but I tried to make
global $dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
That doesn't work too.
Also, it seems that value that are put outside of functions are not global like it would be in js, how can I make something accessible from everywhere (like file that include that file)
Thanks
Better way would be to do something like this:
function getDB(){
$dbh = null;
try {
$dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
return $dbh;
}
And than in your functions do this:
function AddUser()
{
$dbh = getDB();
if(!is_null($dbh)){
$requete = "INSERT INTO users (ip, finish, lastPage) VALUES (".getIPforBDD().", ".false.", questionnaire_initial.php)";
$result = $dbh->query($requete);
}
}
To use $dbh inside a function, you need to include global keyword inside the function scope.
You can find the global keyword explanation here http://php.net/manual/en/language.variables.scope.php#language.variables.scope.global
function AddUser()
{
global $dbh;
$requete = "INSERT INTO users (ip, finish, lastPage) VALUES (".getIPforBDD().", ".false.", questionnaire_initial.php)";
$result = $dbh->query($requete);
}
You may use like this
$host = "localhost";
$dbname = "hawkI";
$user = "root";
$password = "";
$userExist = false;
$userIP = null;
$userHasFinish = null;
$userLastPage = null;
$dbh = NULL;
function db () {
try {
if ($GLOBALS['dbh']===NULL){
$GLOBALS['dbh'] = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
}
return $GLOBALS['dbh'];
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
function SavePageInBDD($page){
$dbh = db();
$requete = "UPDATE users SET lastPage = '.$page.' WHERE ip = ".getIPforBDD();
$result = $dbh->query($requete);
}

Call to a member function query() on null with PDO

I just checked all of the answers are available on stackoverflow,they are similar but not my answer exactly. So please don't take this post as duplicate.
these are my codes when I'm executing it say's
Fatal error: Call to a member function query() on null in
C:\wamp64\www\ourCMS\index.php on line 12
Here is my snippet :
<?php
class DB
{
private $dbHost;
private $dbName;
private $dbUser;
private $dbPass;
protected $con;
function set_db($host, $db, $user, $pass)
{
$this->dbHost = $host;
$this->dbName = $db;
$this->dbUser = $user;
$this->dbPass = $pass;
}
function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
}
}
// here is the place where i'm trying to use this actually
if (isset($_POST['submit']))
{
include('include/database.php');
$database = new DB;
$database->set_db("localhost", "ourcms", "root", "");
$conn = $database->connect();
$name = $_POST['nm'];
$query = "INSERT INTO testingpdo (name) VALUES ('$name')";
$data = $conn->query($query);
$result = $data->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
}
You don't return nothing from DB::connect ($conn = $database->connect();). Add return $this->con; at the end of the function.
function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
return $this->con;
}

Php class inside connection close or class close?

i have php class USER and Database class im doing 10000 users app, and that user will be query 3-4 times a day minumum . my class base and function base here them looking yet for thats have any problem ? or need any fix ?
MY db class
class Database
{
private $host = "";
private $db_name = "";
private $username = "";
private $password = "";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
print'{"success": "0","message": "Service Error, Please try again later "}';
}
return $this->conn;
}
}
Also my USER class here
<?php
require_once('dbconfig.php');
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function updateProduct($name,$code,$description,$quantity,$price,$specialwarning,$productID)
{
try
{
$stmt2 = $this->conn->prepare("UPDATE Products SET productCode='$code',productName='$name',productDescription='$description',specialWarning='$specialwarning',productQuantity='$quantity',productPrice='$price' WHERE ID=$productID");
$stmt2->execute();
echo'{"success": "1", "message": "Product Updated"}';
return true;
}
catch(PDOException $e)
{
}
$this->conn = null; // HERE I DID NULL FOR DISABLE MAX CONNECTIONS
}
}
AND HER MY updateproduct.php
<?php
header('Content-type: application/json');
$name = $_REQUEST['name'];
$code = $_REQUEST['code'];
$description = $_REQUEST['description'];
$quantity = $_REQUEST['quantity'];
$price = $_REQUEST['price'];
$specialwarning = $_REQUEST['specialwarning'];
$productID = $_REQUEST['productID'];
include_once 'class.user.php';
$user = new USER($DB_con);
if($user->updateProduct($name,$code,$description,$quantity,$price,$specialwarning,$productID))
{
}
else
{
}
?>
Can you check my codes is good class for big users ? and good connection returns ? Can i add something ? or need any fix ?Also need to close class ?
Thanks

Mysqli oop method call

I'm really new to implementing OOP using mysqli things, I have this Object(Class) named Database, my real problem is how would I call my select method in my index.php and how can I use it
Database Class.php is below:
Class Database{
private $host = null;
private $user = null;
private $pass = null;
private $db = null;
public $error = "Error Po Sir!";
public $con;
public function connect($host, $user, $pass, $db){
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->db = $db;
$this->con = mysqli_connect($this->host, $this->user, $this->pass);
if(mysqli_connect_errno()){
echo "Connection Failed %s\n!", mysqli_connect_error();
exit();
}
}
public function select($condition){
$query = "select os_user from users WHERE os_user = {$condition}";
$result = mysqli_query($this->con,$query);
return $result;
}
}
this is how did I implement it:
require 'templates/dbclass.php';
$db = new Database();
$db->connect("localhost", "root", "", "os_db");
$username = $_POST['username'];
if($result = $db->select($username)){
echo $username;
if($result->num_rows > 0){
while($row = $result->fetch_object()){
echo $row->os_id;
}
}
}
But it does not show any results. When I var_dump($result) I get bool(false).
I've enabled error reporting, but there is no errors displayed.
There are 3 issues with your select function
is is vulnerable to SQL injection
it does no error checking
it is useless
Here is how it have to be
public function query($sql, $bind)
{
$db = $this->con;
$stm = $db->prepare($sql) or trigger_error($db->error." [$sql]");
$types = str_repeat("s", count($values));
array_unshift($bind, $types);
call_user_func_array(array($stm, 'bind_param'), $bind);
$stm->execute() or trigger_error($db->error." [$sql]");
$stm->store_result();
return $stm->get_result();
}
used like this
$sql = "select os_user from users WHERE os_user = ?";
$res = $db->select($sql, $_POST['username']));
while($row = $result->fetch_object()){
echo $row->os_id;
}

Categories