PHP Pdo: Showing records out of database [duplicate] - php

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 4 years ago.
I want to show all the records from the DB on my website, it's a PDO built website. I want it to show all the records so you can see what's in the DB.
This is how my DB looks like
The connection is set up in a different document called config.php
<?php
date_default_timezone_set('Europe/Amsterdam');
error_reporting(E_ALL & ~ E_DEPRECATED);
ini_set('display_errors', 'ON');
$CONFIG = array();
$CONFIG['root'] = '/home/tom/public_html';
$CONFIG['rootwebsite'] = '/home/tom/public_html';
$CONFIG['website'] = 'https://###';
$CONFIG['dbhost'] = 'localhost';
$CONFIG['dbuser'] = '####';
$CONFIG['dbpass'] = '####';
$CONFIG['dbdatabase'] = 'tom';
?>
This is the code I have in a php document and tried using. The problem is it won't show anything on my website (this is a different file than the file my website is):
<?php
class Forum {
private $dbh; //dbh = database handler.
public function __construct($database) {
$this->dbh = $database;
}
public function getForum() {
$getTopic = $dbh->prepare("SELECT * FROM topics ORDER BY id DESC");
$getTopic->execute();
$topics = $getUTopic->fetchAll();
foreach ($topics as $topic) {
echo $topic['onderwerp'] . '<br />';
}
}
}

You are not calling the right $connection variable. It should be $this->dbh
$getTopic = $this->dbh->prepare("SELECT * FROM topics ORDER BY id DESC");
Also you are mixing the variables after execute(). You should use easy to remember variables.
public function getForum() {
try {
$getTopic = $this->dbh->prepare("SELECT * FROM topics ORDER BY id DESC");
$getTopic->execute();
$topics = $getTopic->fetchAll();
foreach ($topics as $topic) {
echo $topic['onderwerp'] . '<br />';
}
} catch (PDOException $pdoEx) {
echo $pdoEx->getMessage();
exit;
} catch (Exception $ex) {
echo $ex->getMessage();
exit;
}
}
Also since you are not passing any variable to your query, there is no point of using prepare(). Just call query() instead.
For error reporting add,
error_reporting(E_ALL); #place at the top of the script
Also you should consider using a proper IDE like PHPstorm or Netbeans, as they would easily point out unsed variables
As suggested by #adpro, here is a link, to help with debugging

Related

I cannot figure out why DeleteTask.php does not work, yet RetrieveTask.php does

I cannot for the life of me figure out why the DeleteTask function will not work, when it is almost the same as RetrieveTask; only called in different files.
Now:
src/controller/RetrieveTask:
prepares a PDO database query, and passes it to src/view/DisplayTask.php, which uses a for each-loop to echo the rows and an <a> element linking to src/redir/DeleteAndReturn.php.
This file simply executes src/controller/DeleteTask.php and src/controller/ReturnToIndex.php.
The file code and order is as follows:
RetrieveTask
<?php
function RetrieveTask($db)
{
$sql = 'SELECT * FROM task';
return $db->query($sql);
}
?>
Which gets passed to DisplayTask:
<?php
function DisplayTask($db)
{
foreach (RetrieveTask($db) as $row)
{
echo "<li>" . $row['tsk-name'] . "<br>" . $row['tsk-desc'] . "<a id=".$row['id']." class='btn btn-danger' href='/todo/redir/DeleteAndReturn.php'>Delete</a>" . "</li>";
}
}
?>
Which get passed to index.php in the /todo/home directory. All I need to do is call DisplayTask($DbHandler) Where $DbHandler is an instant of the db class.
Now for src/controller/DeleteTask.php:
<?php
function DeleteTask($db)
{
echo "Delete";
$sql = ' DELETE FROM task where id= 2 ';
return $db->query($sql);
}
?>
and src/controller/ReturnToIndex.php:
<?php
function ReturnToIndex()
{
header('Location: /todo/home');
}
?>
Leads to redir/DeleteAndReturn.php
<?php
include_once('../src/model/db/DbConnect.php');
include_once('../src/controller/DeleteTask.php');
include_once('../src/controller/ReturnToIndex.php');
$DbHandler = new DbConnect();
DeleteTask($DbHandler);
$DbHandler->CloseConnection();
ReturnToIndex();
?>
I've tried passing the item id as a get parameter in a query string. Deleting all tables. Manually selecting the id. I can't get it to work. Any help would be much appreciated. I googled and looked up documentation for hours. I feel like it is something exceedingly simple that just went way over my head.
Full code is here: https://github.com/liengesbor.
As maxim_039 suggested, I changed how a variable array was passed to the DB construct. Somehow this fixed the issue.
function __construct()
{
- parent::__construct('mysql:host=localhost;dbname=todo;', 'root', 'alexel', array ('$opt'));
+ parent::__construct('mysql:host=localhost;dbname=todo;', 'root', 'alexel', $this->opt);
echo "Connected to Database";
}
Here is the database code:
<?php
// Connect to the database using PDO and MySQL
class DbConnect extends PDO
{
protected $dsn = "mysql:host=localhost;dbname=todo;";
protected $dbPassword = 'alexel';
protected $dbUsrName = 'root';
protected $opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
function __construct()
{
parent::__construct('mysql:host=localhost;dbname=todo;', 'root', 'alexel', $this->opt);
echo "Connected to Database";
}
function CloseConnection()
{
$this->DbConnection = null;
}
}
?>

why is my class not working? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Guys i'm scratching my head for this problem. As, i get this error from my openshift log
PHP Fatal error: Call to a member function totalids() on a
non-object in
/var/lib/openshift/573dc0da2d5271d357000294/app-root/runtime/repo/st&com.php
on line 46, referer: http://express-pad4u.rhcloud.com/
And doing var_dump on $conn and $project from dbconfig.inc.php file in st&com.php gives the following message:
object(PDO)#1 (0) { } object(projecteg)#2 (4) {
["_db":"projecteg":private]=> object(PDO)#1 (0) { } ["query"]=> NULL
["stmth"]=> NULL ["conn"]=> NULL }
here is my dbconfig.inc.php code:
session_start();
define('DB_HOST', getenv('OPENSHIFT_MYSQL_DB_HOST') . ':' . getenv('OPENSHIFT_MYSQL_DB_PORT'));
define('DB_USER', getenv('**********'));
define('DB_PASS', getenv('**********'));
define('DB_BASE', 'project');
define('DB_PORT', getenv('OPENSHIFT_MYSQL_DB_PORT'));
try {
$conn = new PDO("mysql:host=" . getenv('OPENSHIFT_MYSQL_DB_HOST') . ";dbname=" . DB_BASE . "", "********", "*********");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $exc) {
echo $exc->getMessage();
}
include 'classes.inc.php';
$project = new projecteg($conn);
here is the code for st&com.php file:
<?php
//error_reporting(0);
include_once "includes/dbconfig.inc.php";
$status_replies="";
$status_list="";
$statusui_edit="";
$isowner="";
$is_friend="";
$statusdeletebutton='';
$reply_delete_button="";
$load= (int)($_POST['load'])*2;
var_dump($conn);
echo '<br>';
var_dump($project);
echo '<br>';
function hashtags($dat) {
$regex="/#+([a-zA-z0-9._-]+)/";
$dat1= preg_replace($regex, '$0', $dat);
return $dat1;
}
function taggingsys($dat) {
$regex="/#+([a-zA-z0-9!._-]+)/";
$dat1= preg_replace($regex, '$0', $dat);
return $dat1;
}
function ff(&$s) {
//$conn="";
//require_once 'includes/dbconfig.inc.php';
$output=array();
// $friends=array();
//$project= new \projecteg($conn);
// $totalids=array();
$verify_friend=array();
foreach ($s as $i=> $r ){
//array_push($friends, $r);
$r["friend_one"] == $_SESSION['uname'] ? $friends[]= $r["friend_two"] : $friends[] = $r["friend_one"];
echo '<pre>';var_dump($friends);echo '</pre>';
$verify_friend= $project->totalids($friends[$i]);
/* foreach ($friends as $v) {
echo '<br><h1>'; print_r($v); echo '</h1></br>';
echo '<br>';
// var_dump($verify_friend);
// array_push($totalids, $verify_friend);
}
echo '<pre>'; var_dump($verify_friend); echo '</pre>'; */
array_push($output, $verify_friend);
}
return $output;
}
$f = array();
$stmt= $conn->prepare("select friend_one, friend_two from friends where (friend_one=:session OR friend_two=:session) and accepted='1'");
$stmt->bindparam(":session",$_SESSION['uname']);
$stmt->execute();
$f=$stmt->fetchAll();
$ids= ff($f);
foreach ($ids as $i=>$v){
$id=$v[$i]['user_id'];
//fetch user_id from update table in db and inject it to the feed query.
$totalUpdates=$project->totalUpdates1($id,$load);
$total_sess_count=$project->totalupdatescount($id);
foreach ($totalUpdates as $j=>$row1) {
$updateid=$row1['update_id'];
$account_name=$row1['account_name'];
$u_id=$row1['user_id_u'];
$author=$row1['author'];
$post_date=$row1['time'];
$title= stripslashes($row1['title']);
$data= stripslashes($row1['update_body']);
$data1= hashtags($data);
//$data1= taggingsys($data0);
$pic=$project->viewByUname($author);
$uid=$pic['user_id'];
$datemade = strftime("%B %d", strtotime($post_date));
$avatar=$pic['avatar'];
if ($avatar!=""){
$feed_pic='user/'.$uid.'/'.$avatar;
} else {
$feed_pic='img/avatardefault.png';
}
//other lengthy logic
here is the class logic:
<?php
class projecteg
{
private $_db;
public $query;
public $stmth;
public $conn;
public function __construct($conn)
{
$this->_db = $conn;
}
public function totalids($friend)
{
try {
$sql2 = "select user_id from user where uname=:session or uname=:friend and activated='1'";
$stmth = $this->_db->prepare("$sql2");//Check here syntax of $db
$stmth->bindValue(":session", $_SESSION['uname']);
$stmth->bindValue(":friend", $friend);
$stmth->execute();
return $stmth->fetchAll();
} catch(PDOException $exc) {
echo $exc->getMessage();
}
}
}
how do i make my method and conn to work.
You are trying to use $project inside a function ff() without passing it in or declaring it inside the function so it doesn't exist inside the scope of that function. Do some research on scope that should help you out. But for now you need to pass in $project to ff() if you want to use it. Something like this:
function ff(&$s,$project) {
...
}
$ids = ff($f,$project);
That is assuming you want to use the $project you have already declared. If not you will need to create a new instance inside the function like Patrick-Q said in the comments.

PHP/MySQL Function Causes Others to Stop Working

I have 3 PHP files: an index.php, a config.php w/ MySQL database definitions and a functions.php file with three separate functions. When only one of the functions is called in the index file, things work fine. When I add just one of the other two, however, things stop working.
Using the following example/files, I get this error message where the second function falls in the index.php code:
Error: Fatal error: Call to a member function query() on a non-object in...line 37, which corresponds to the DB query in that second function-- the get_chapter_dollars function.
I'm sure it's something simple, but what am I missing, here? Why is that second function causing problems?
CONFIG.PHP
<?php
define("BASE_URL","/dayofgiving/");
define("ROOT_PATH",$_SERVER["DOCUMENT_ROOT"] . "/dayofgiving/");
// Set variables for the database.
define("DB_HOST", "localhost");
define("DB_NAME", "cdwyer_dspdog");
define("DB_PORT", "1234");
define("DB_USER", "user");
define("DB_PASS", "pass");
FUNCTIONS.PHP
<?php
require_once($_SERVER["DOCUMENT_ROOT"] . "/dayofgiving/inc/config.php");
function get_state_stats() {
require_once(ROOT_PATH . "inc/db.php");
try {
$results = $db->query("
SELECT abb, fullname, dollars, alumnidollars, ugdollars, donors, alumnidonors, ugdonors
FROM dog_states");
$maxDollars = $db->query("
SELECT MAX(dollars)
FROM dog_states;
");
} catch (Exception $e) {
echo "Data coudn’t be found.";
exit;
}
$maxDollars = intval($maxDollars->fetchColumn(0));
$stateInfo=array();
while ($row = $results->fetch(PDO::FETCH_ASSOC)) { // Will return boolean(false) when condition is no longer met.
$stateAbb = $row["abb"];
$thisDollars = $row["dollars"];
$stateInfo[$stateAbb] = $row; // Loops through all states/rows one at a time, and adds all properties to the stateInfo variable w/ abbreviation as key.
$stateInfo[$stateAbb]["opacity"] = ((($thisDollars / $maxDollars)*.5)+.5);
}
return $stateInfo;
}
function get_chapter_dollars() {
require_once(ROOT_PATH . "inc/db.php");
try {
$dollarResults = $db->query("
SELECT abb, fullname, dollars
FROM dog_chapters
ORDER BY dollars DESC
LIMIT 5");
} catch (Exception $e) {
echo "Data coudn’t be found.";
exit;
}
$chapterDollars=array();
while ($row = $dollarResults->fetch(PDO::FETCH_ASSOC)) { // Will return boolean(false) when condition is no longer met.
$chapterDollars[] = $row; // Loops through all (ie, top 5) chapters/rows one at a time, and adds all properties to the chapterDollars variable w/ number as key.
}
return $chapterDollars;
}
function get_chapter_donors() {
require_once(ROOT_PATH . "inc/db.php");
try {
$donorResults = $db->query("
SELECT abb, fullname, donors
FROM dog_chapters
ORDER BY donors DESC
LIMIT 5");
} catch (Exception $e) {
echo "Data coudn’t be found.";
exit;
}
$chapterDonors=array();
while ($row = $donorResults->fetch(PDO::FETCH_ASSOC)) { // Will return boolean(false) when condition is no longer met.
$chapterDonors[] = $row; // Loops through all (ie, top 5) chapters/rows one at a time, and adds all properties to the chapterDollars variable w/ number as key.
}
return $chapterDonors;
}
?>
INDEX.PHP (portion)
<?php require_once($_SERVER["DOCUMENT_ROOT"] . "/dayofgiving/inc/config.php"); ?>
<?php require_once(ROOT_PATH . "db/functions.php"); ?>
<?php $tempStateStats = get_state_stats() ?>
var jsonStates = <?php echo json_encode($tempStateStats); ?>;
<?php $returnChapterDollars = get_chapter_dollars() ?>
<?php echo $returnChapterDollars[0]["abb"];?>
I've had issues with require_once working correctly with my version of PHP (5.3.3). For the purpose of testing try changing it to require or include for each instance on the page and see if it works.

PHP OOP - Trying to call a method

Just trying to get my head around OOP. I have been told that I am doing the script below wrong. I was previously trying to call a method from the database class. When really the database class should only be dealing with database stuff. So I have now created an html_class.php where I believe I need to access the database class and then output the html via this class?.
The method I am trying to call on the index.php is the getBlogPost()method located in the html_class.php file. I am trying to call this using echo $htmlObject->getBlogPosts();
I am assuming this is the proper way to go about doing this?
I am currently getting the following errors:
Notice: Undefined variable: db_login_info in C:\xampp\htdocs\xampp\oop\CMS\classes\html_class.php on line 14
Fatal error: Cannot access private property database::$objDbConn in C:\xampp\htdocs\xampp\oop\CMS\classes\html_class.php on line 15
index.php
<?php
require_once("includes/header.php");
require_once("includes/footer.php");
require_once("classes/database_class.php");
require_once("classes/blog_post_class.php");
require_once("classes/html_class.php");
require_once("conf/config.php");
$header = new header();
// createHeader( Title | Description | Keywords)
echo $header->createHeader('Home - Nissan Skyline GTR Blog', 'This is a blog site about the Nissan GTR', 'Nissan, GTR, R35');
$dbObject = new database($db_login_info);
$htmlObject = new makeHTML();
?>
<div id="container">
<div id="top_nav">
Admin Login
</div>
<div id="header"></div>
<div id="nav">
<ul>
<li>Home</li>
<li>Create Blog</li>
<?php
$sql = "SELECT * FROM create_page";
echo $dbObject->createNavigation($sql);
?>
</ul>
</div>
<div id="content_area">
<?php
echo $htmlObject->getBlogPosts(); // Calling the getBlogPost function located in the html_class.php
// echo $dbObject->getBlogPosts();
?>
</div>
<?php
$footer = new footer();
echo $footer->createFooter();
?>
database_class.php
<?php
class database {
private $objDbConn;
function __construct($db_login_info){
$this->objDbConn = new mysqli($db_login_info['host'], $db_login_info['username'],
$db_login_info['password'], $db_login_info['database']);
if (mysqli_connect_errno()) {
die("Database connection failed". mysqli_connect_error());
}
}
// I was previoulsy calling this method below on the index.php page and it was working great
// function getBlogPosts(){
// $objRes = mysqli_query($this->objDbConn, "SELECT * FROM `blog_posts` ORDER BY id DESC");
// if(mysqli_errno($this->objDbConn)) {
// die("Failed query: $strSql". $this->objDbConn->error);
// }
// $allrows ='';
// while ($row = mysqli_fetch_array($objRes)) {
// $time = strtotime($row['date']);
// $my_format = date("m/d/y # g:ia", $time);
// $allrows .= '<div id="blog_post">';
// $allrows .= '<h2 id="blog_title">'.$row['title'].'</h2>';
// $allrows .= '<h5> Posted on the '.$my_format.'</h5>'."<br>";
// $allrows .= '<div id="blog_content">'.nl2br($row['content']).'</div>'."<br>";
// $allrows .= '<b>ID:</b>'.$row['id'].' Delete</div>';
// };
// return $allrows;
// }
?>
html_class.php
<?php
require_once("includes/header.php");
require_once("includes/footer.php");
require_once("classes/database_class.php");
require_once("classes/blog_post_class.php");
require_once("classes/html_class.php");
require_once("conf/config.php");
class makeHTML {
function getBlogPosts(){
$dbObject = new database($db_login_info); // This is where the Notice: Undefined variable: db_login_info is happening
$objRes = mysqli_query($dbObject->objDbConn, "SELECT * FROM `blog_posts` ORDER BY id DESC");
if(mysqli_errno($dbObject->objDbConn)) {
die("Failed query:". $dbObject->objDbConn->error);
}
$allrows ='';
while ($row = mysqli_fetch_array($objRes)) {
$time = strtotime($row['date']);
$my_format = date("m/d/y # g:ia", $time);
$allrows .= '<div id="blog_post">';
$allrows .= '<h2 id="blog_title">'.$row['title'].'</h2>';
$allrows .= '<h5> Posted on the '.$my_format.'</h5>'."<br>";
$allrows .= '<div id="blog_content">'.nl2br($row['content']).'</div>'."<br>";
$allrows .= '<b>ID:</b>'.$row['id'].' Delete</div>';
};
return $allrows;
}
}
?>
config.php
<?php
// Database login details below
$db_login_info = array(
'host'=>'localhost',
'username'=>'root',
'password'=>'',
'database'=>'cms'
);
?>
Updated html_class.php
<?php
require_once("includes/header.php");
require_once("includes/footer.php");
require_once("classes/database_class.php");
require_once("classes/blog_post_class.php");
require_once("classes/html_class.php");
require_once("conf/config.php");
class makeHTML {
private $database;
public function __construct(database $database){
$this->database = $database;
}
function getBlogPosts(){
$objRes = mysqli_query($this->database, "SELECT * FROM `blog_posts` ORDER BY id DESC");
if(mysqli_errno($this->database)) {
die("Failed query:". $this->database->error);
}
$allrows ='';
while ($row = mysqli_fetch_array($objRes)) {
$time = strtotime($row['date']);
$my_format = date("m/d/y # g:ia", $time);
$allrows .= '<div id="blog_post">';
$allrows .= '<h2 id="blog_title">'.$row['title'].'</h2>';
$allrows .= '<h5> Posted on the '.$my_format.'</h5>'."<br>";
$allrows .= '<div id="blog_content">'.nl2br($row['content']).'</div>'."<br>";
$allrows .= '<b>ID:</b>'.$row['id'].' Delete</div>';
};
return $allrows;
}
}
Update database_class.php
class database {
public $objDbConn;
function __construct($db_login_info){
$this->objDbConn = new mysqli($db_login_info['host'], $db_login_info['username'],
$db_login_info['password'], $db_login_info['database']);
if (mysqli_connect_errno()) {
die("Database connection failed". mysqli_connect_error());
}
}
?>
fetchall method in database_class.php:
function fetchall($sql) {
$query = mysqli_query($this->objDbConn, $sql);
if ($this->objDbConn->connect_errno) {
die("Database connection failed with message: " . $objDbConn->connect_error);
}
}
You should use "Dependency Injection" to give your makeHtml class the database object.
Add a __construct method to your makeHtml class:
class makeHtml
{
private $database;
public function __construct(database $database)
{
$this->database = $database;
}
When you instantiate your makeHtml class:
$htmlObject = new makeHTML($dbObject);
Then inside your class, instead of creating a new database object (and a new connection every time) you can just refer to your database object with $this->database.
Further note to your case above, you will need to make the $objDbConn variable in the database class public so that you can access that variable in the other class. However, it would be "good practice" to have a method within your database class that deals with performing queries and returning the result. Ideally you should end up with something like:
$sql = 'SELECT * FROM `blog_posts` ORDER BY id DESC';
$allRows = $this->database->fetchAll($sql);
That will appear in your makeHtml class.
Okay, a few different things are going on with your code.
For starters, you are mixing procedural and object-oriented versions of MySQLi. The fact that you are using MySQLi is a big plus instead of going with the old deprecated version of MySQL. However, you need to pick between procedural or OOP, and then stick with it.
As for your error messages. You are getting the notice about $db_login_info because it does not exist in the getBlogPosts() method. When you are inside of a method your variable scope becomes limited. Meaning that variables declared outside of it are not visible within the method unless they are passed in as parameters.
The second message is about class scope. Your variable $dbObjConn is declared as private, which is fine, but you can only access a private variable from within the same class. If you declare it public then you can access it the way you are.
So here are some modifications I can suggest making to your code. Having a database class isn't a bad thing, it is easier to create a connection as an object and then pass that object around to other classes that need it. But, when you do this you should not mix the procedural versions of MySQLi with the OOP version. (I recommend you stick with the OOP version).
Your database_class.php could look something like this:
class database {
private $objDbConn;
function __construct($db_login_info){
$this->objDbConn = new mysqli($db_login_info['host'], $db_login_info['username'],
$db_login_info['password'], $db_login_info['database']);
//This is where you are using the procedural interface
//if (mysqli_connect_errno()) {
// die("Database connection failed". mysqli_connect_error());
// }
//}
//Use the OOP version instead
if ($this->objDbConn->connect_errno) {
die("Database connection failed with message: " . $this->objDbConn->connect_error);
}
}
//Keep populating this class with more stuff. Like:
public function getDB() {
return $this->dbObjConn; //use this method to access your private database variable from outside the class
}
}
The html_class.php file could use some love as well:
class makeHTML {
private $database; //Here is a place for your shiny database object.
public functon __construct($database) {
$this->database = $database;
}
public function getBlogPosts() {
$dbObject = $this->database->getDB();
$objRes = $dbObject->query($dbObject->objDbConn, "SELECT * FROM `blog_posts` ORDER BY id DESC");
if($dbObject->errno) {
die("Failed query:". $dbObject->error);
}
$allrows ='';
while ($row = $objRes->fetch_array()) {
$time = strtotime($row['date']);
$my_format = date("m/d/y # g:ia", $time);
$allrows .= '<div id="blog_post">';
$allrows .= '<h2 id="blog_title">'.$row['title'].'</h2>';
$allrows .= '<h5> Posted on the '.$my_format.'</h5>'."<br>";
$allrows .= '<div id="blog_content">'.nl2br($row['content']).'</div>'."<br>";
$allrows .= '<b>ID:</b>'.$row['id'].' Delete</div>';
};
return $allrows;
}
//Again, keep adding more to this class as you see fit....
}
Then to put all of this together, your calling code would look something like:
<?php
include "config.php";
$myDatabase = new database($db_login_info);
$html = new makeHTML($myDatabase);
$posts = $html->getBlogPosts();
print($posts);
?>
you cannot use private member of object. Instead you could use method or make member public.
Also instead of creating connection object every time you should create connection object in config file and include this file once.

Can I improve my PDO method (just started)

I just switched to PDO from mySQLi (from mySQL) and it's so far good and easy, especially regarding prepared statements
This is what I have for a select with prepared statement
Main DB file (included in all pages):
class DBi {
public static $conn;
// this I need to make the connection "global"
}
try {
DBi::$conn = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuname, $dbpass);
DBi::$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
DBi::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo '<p class="error">Database error!</p>';
}
And in my page:
try {
$sql = 'SELECT pagetitle, pagecontent FROM mypages WHERE pageid = ? LIMIT 1';
$STH = DBi::$conn->prepare($sql);
$STH->execute(array($thispageid)); // $thispageid is from a GET var
}
catch(PDOException $e) {
echo '<p class="error">Database query error!</p>';
}
if ($STH) { // does this really need an if clause for it self?
$row = $STH->fetch();
if (!empty($row)) { // was there found a row with content?
echo '<h1>'.$row['pagetitle'].'</h1>
<p>'.$row['pagecontent'].'</p>';
}
}
It all works. But am I doing it right? Or can I make it more simple some places?
Is using if (!empty($row)) {} an ok solution to check if there was a result row with content? Can't find other decent way to check for numrows on a prepared narrowed select
catch(PDOException $e) {
echo '<p class="error">Database query error!</p>';
}
I would use the opportunity to log which database query error occurred.
See example here: http://php.net/manual/en/pdostatement.errorinfo.php
Also if you catch an error, you should probably return from the function or the script.
if ($STH) { // does this really need an if clause for it self?
If $STH isn't valid, then it should have generated an exception and been caught previously. And if you had returned from the function in that catch block, then you wouldn't get to this point in the code, so there's no need to test $STH for being non-null again. Just start fetching from it.
$row = $STH->fetch();
if (!empty($row)) { // was there found a row with content?
I would write it this way:
$found_one = false;
while ($row = $STH->fetch()) {
$found_one = true;
. . . do other stuff with data . . .
}
if (!$found_one) {
echo "Sorry! Nothing found. Here's some default info:";
. . . output default info here . . .
}
No need to test if it's empty, because if it were, the loop would exit.

Categories