Get results from from MySQL using PDO - php

I'm trying to retrieve data from my table using PDO, only I can't seem to output anything to my browser, I just get a plain white page.
try {
// Connect and create the PDO object
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
$lastIndex = 2;
$sql = "SELECT * FROM directory WHERE id > :lastIndex AND user_active != '' LIMIT 20"
$sth = $conn->prepare($sql);
$sth->execute(array(':lastIndex' => $lastIndex));
$c = 1;
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo 'ALL STYLING ETC RESULTS HERE';
$c++;
}
$conn = null; // Disconnect
}

EXAMPLE.
This is your dbc class
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getAllData($qty) {
//prepared query to prevent SQL injections
$query = "select * from TABLE where qty = ?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $qty, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
$getList = $db->getAllData(25);
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}

Related

PDO DELETE is not deleting all the row

I have the codes following for a delete process;
if(isset($_POST['deleteSong'])) {
$id = $_POST['deleteSong'];
$delete = $connect->prepare('DELETE FROM lyrica_songs WHERE id = ?');
$delete->execute(array($id));
$error = TRUE;
}
These codes is not deleting row. I have 7 columns at lyrica_songs and 3 of them are integers. ID (auto increment), song_singer_id and song_hit and when i run my codes ID, song_singer_id, song_hit are not deleted. I tried making them text instead integers and ID and song_hit still can't be deleted.
EDIT:
My connection code
<?php
$db_host = 'mysql:host=localhost;dbname=lyrica;charset=utf8';
$db_username = 'root';
$db_password = '';
try {
$connect = new PDO($db_host,$db_username,$db_password);
$connect->exec('SET NAMES UTF-8; SET CHARACTER SET UTF-8');
} catch (PDOException $error) {
echo "Veritabanı bağlantısı kurulamadı: " . $error->getMessage();
}
PDO version of #ChukwuemekaInya code
$db_host = 'localhost';
$db_username = 'root';
$db_password = '';
try {
$query = "DELETE FROM `lyrica_songs` WHERE `id`=:id ";
$dB = new PDO("mysql:host=$db_host;dbname=lyrica", $db_username, $db_password);
$stmt = $dB->prepare($query);
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
return $stmt->execute();
} catch (PDOException $e) {
echo $e->getMessage();
return false;
}
$db_host = 'localhost';
$db_username = 'root';
$db_password = '';
try {
$connect = new PDO("mysql:host=$db_host;dbname=lyrica",$db_username,$db_password);
} catch (PDOException $error) {
echo "Veritabanı bağlantısı kurulamadı: " . $error->getMessage();
}
$delete = $connect->prepare('DELETE FROM lyrica_songs WHERE id = :id');
$delete->bindParam(':id', $id);
$delete->execute();
$delete->close();

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

PHP: Prepared Statements inside a OOP based project

I'm a little confused about Prepared Statements in PHP, I've been watching the following tutorial on youtube: https://www.youtube.com/watch?v=aN5KqxK1slc
After I've received the following note on my currently Mysqli source code:
You are wide open to SQL Injections and should really use Prepared
Statements instead of concatenating your queries. Specially since
you're not escaping the user inputs at all!
My question:
How would I prepare the statement since I'm creating the syntax for the statement inside my register class and only pass the statement to my database class to execute it using the execute_query function?
Would I just prepare the statement inside the execute_query function and check if its either a statement of the format INSERT or SELECT and then prepare the values?
I appreciate any kind of suggestions and feedback.
My current code looks like the following:
Register class:
<?php
class register extends database
{
function __construct($username, $password, $email)
{
$this->username = $username;
$this->password = password_hash($password, PASSWORD_DEFAULT);
$this->email = $email;
$this->activation_id = $this->generateActivationId();
$this->sender_email = 'support#url.com';
$this->activation_link = 'http://url.com/folder/activate.php?id=' . $this->activation_id;
$this->database = new database();
}
function generateActivationId()
{
$generator = bin2hex(random_bytes(10));
return $generator;
}
function registerAccount()
{
$this->database->connect();
$user_lookup = $this->database->execute_query("SELECT * FROM users WHERE username = '" . $this->username . "'");
if (mysqli_num_rows($user_lookup) > 0)
{
return false;
}
else
{
$this->database->execute_query("INSERT INTO users (username, password, email, activation_id) VALUES ('" . $this->username . "', '" . $this->password . "', '" . $this->email . "', '" . $this->activation_id . "')");
$user_lookup_comfirm = $this->database->execute_query("SELECT * FROM users WHERE username = '" . $this->username . "'");
if (mysqli_num_rows($user_lookup_comfirm) > 0)
{
$this->sendRegisterEmail();
return true;
}
else
{
return false;
}
}
}
function sendRegisterEmail()
{
$subject = 'Registration - Activate your account';
$message = 'Thank you for registering. Please activate your account by visiting the following site: Website link';
$headers = 'From: ' . $this->sender_email . "\r\n" .
'Reply-To: ' . $this->sender_email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($this->email, $subject, $message, $headers);
}
}
?>
Database class:
<?php
class database
{
function __construct()
{
$this->dBusername = 'xxx';
$this->dBpassword = 'xxx';
$this->dBhost = 'localhost';
$this->dBdatabase = 'xxx';
$this->dBcharset = 'utf8';
}
function connect()
{
$mysqli = new mysqli($this->dBhost, $this->dBusername, $this->dBpassword, $this->dBdatabase);
if ($mysqli->connect_errno)
{
$this->_mysqli = false;
}
else
{
$mysqli->set_charset($this->charset);
$this->_mysqli = $mysqli;
}
}
function execute_query($sql)
{
if($results = $this->_mysqli->query($sql))
{
return $results;
}
else
{
return false;
}
}
}
?>
<?php
class Config{
private function Db(){
$db = null;
$dsn = UR DSN;
$user = UR USER;
$pass = UR PASS;
try{
$db = $pdo = new PDO($dsn, $user, $pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_TIMEOUT => "10"));
return $db;
} catch(Exception $e){
var_dump($e);
}
return null;
}
function execPreparedStatement($sql , Array $param = null){
try{
$db = $this->Db();
if($db != null && ($db instanceof PDO)){
$db->beginTransaction();
$stm = $db->prepare($sql);
for ($i = 0 ; $i < count($param) ; $i++){
$stm->bindValue($i + 1,$param[$i]);
}
$dat = $stm->execute();
$db->commit();
$stm = null;
$db = null;
return $dat;
}
} catch (PDOException $e) {
$db->rollBack();
var_dump("<br><br>Error: ".$e->getMessage().' in '.$e->getFile().' on line '.$e->getLine(), $sql, $param);
}
}
function getPreparedStatement($sql , Array $param = null,$type = null) {
$db = $this->Db();
if($db != null && ($db instanceof PDO)) {
$stm = $db->prepare($sql);
if(!empty($param)){
for ($i = 0 ; $i < count($param) ; $i++){
$stm->bindParam($i+1, $param[$i]);
}
}
try {
$stm->execute();
if($type) {
$dat = #$stm->fetchAll(PDO::FETCH_ASSOC);
} else {
$dat = #$stm->fetchAll();
}
$stm = null;
$db = null;
return $dat;
} catch (Exception $e){
var_dump("<br><br>Error capturado: ".$e->getMessage().' in '.$e->getFile().' on line '.$e->getLine(),$sql,$param);
}
}
}
}
this is a PDO class u can use it as this
<?php
$db = new Config();
// This is for an update
$db->execPreparedStatement('update table set a = ?, b = ? where id = ?)', array(value1, value2, id));
// Select With out filter
$data = $db->getPreparedStatment('select * from table');
// With Filter.
$data = $db->getPreparedStatment('select * from table where id = ?', array(id));
this is just and example i can give u more feed back if u need. but i think with this u can do it on ur own

PHP PDO is not displaying any data on my web page

I've recently tried to convert my procedural MySQL queries to PDO statements. I've copied the following code from php official documentation and added my parameters to it. It is not showing any results in the page.
<?php
$dsn = 'mysql:host=localhost;dbname=database';
$user = 'user';
$pass = 'pass';
try {
$dbh = new PDO($dsn , $user, $pass);
$dbh = null;
} catch (PDOException $e) {
print "An error has occurred. Please contact support. <br/>" . $e->getMessage() . "<br/>";
die();
}
$value = 'user1';
$stmt = $dbh->prepare("SELECT * FROM table where username = ?");
if ($stmt->execute(array($value))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
?>
Try this:-
<?php
$dsn = 'mysql:host=localhost;dbname=databasename';
$user = 'user';
$pass = 'password';
try {
$dbh = new PDO($dsn , $user, $pass);
} catch (PDOException $e) {
print "An error has occurred. Please contact support. <br/>" .
$e->getMessage() . "<br/>";
die();
}
$value = 'user1';
$stmt = $dbh->prepare("SELECT * FROM table where column= ?");
if ($stmt->execute(array($value))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>

Querying two databases with PDO

I'm trying to change my queries from mysql to PDO because I need to query at the same time two different databases on different servers.
I've done these classes so far
class Db extends PDO {
public $db;
public function __construct($dbhost = 'host1', $dbname = 'db1', $dbuser = 'user1', $dbpass = 'user2', $dbtype = 'mysql') {
PDO::__construct($dbtype . ':host=' . $dbhost . ';dbname=' . $dbname, $dbuser, $dbpass);
}
function sql_query($sql) {
$result = PDO::query($sql);
return $result;
}
function sql_fetcharray($result) {
$rs = $result->fetch(PDO::FETCH_ASSOC);
return $rs;
}
function sql_numrows($result) {
$rs = $result->rowCount();
return $rs;
}
}
class Db2 extends Db {
public $db;
public function __construct($dbhost = 'host2', $dbname = 'db2', $dbuser = 'user2', $dbpass = 'pass2', $dbtype = 'mysql') {
PDO::__construct($dbtype . ':host=' . $dbhost . ';dbname=' . $dbname, $dbuser, $dbpass);
}
function sql_query($sql) {
parent::sql_query($sql);
$result = PDO::query($sql);
return $result;
}
function sql_fetcharray($result) {
$rs = $result->fetch(PDO::FETCH_ASSOC);
return $rs;
}
function sql_numrows($result) {
$rs = $result->rowCount();
return $rs;
}
}
and then
$db = new Db2;
$sql = "query";
$result = $db->sql_query($sql);
but the query affects only the second database.
Anyone can help?
Thanks a lot
you had to run your query twice against two databases. don't expect the inheritance to do that for you
$db = new Db2();
$sql = "query";
$result = $db->sql_query($sql);
$db1 = new Db();
$sql = "query";
$result1 = $db1->sql_query($sql);
I don't think you needed another child class, you can easily switch database using :
USE DATABASENAME
So for example you can do:
$db = new Db;
$sql = "query";
$result = $db->sql_query($sql);
$db->sql_query('USE DB2');
$sql2 = "query2";
$result2 = $db->sql_query($sql2);
or perhaps create a function to select db:
function select_db($db) {
$result = PDO::query('USE $db');
return $result;
}
then use it:
$db = new Db;
$sql = "query";
$result = $db->sql_query($sql);
$db->select_db('DB2');
$sql2 = "query2";
$result2 = $db->sql_query($sql2);

Categories