OOP PDO fetch while loop - php

I have a function in my class which is not completed. I'm searching a way to do it all night long. Well I want to fetch all the result of a SELECT request to MYSQL using PDO in a OOP class/function.
Here my function
function select($query)
{
try
{
$sql = $this->connect->query($query);
while ($row = $sql->fetch(PDO::FETCH_ASSOC))
{
return ????
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
I know that I can do it with a while loop, I tested a few options but most of the time I only got 1 result. Anyone a point for me, where I could start my search for a solution to this issue?

It's pretty easy, actually. You use PDO::FETCH_CLASS and specify which class you want to instantiate for each row.
Here is an example that fetches all available rows as an array of objects of class YourClassName.
function select($query) {
try {
$sql = $this->connect->query($query);
return $sql->fetchAll(PDO::FETCH_CLASS, YourClassName);
} catch(PDOException $e) {
echo $e->getMessage();
}
}

Only use $sql->fetch(PDO::FETCH_ASSOC) within the while loop, not before, as you have it.
So, like:
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
// something
}

Related

PHP : Returning two separate queries different results within a function in php

i used two functions to get two different query results.
Can i get these two different query results using one function??
Thanks for any help
you can provide.
public function referralDoctorData($ReferredByIdUser)
{
try
{
$referralDoctorDataQuery = $this->PDOconn->prepare("
SELECT * FROM tuserlist AS a
LEFT JOIN tdoctorprofilelist AS b
ON a.IdUser = b.RefIdUser
WHERE
a.IdUser = $ReferredByIdUser
");
$referralDoctorDataQuery->execute();
$referralDoctorData = $referralDoctorDataQuery->fetch();
return $referralDoctorData;
}
catch(PDOException $e)
{
return $e->getMessage();
}
}
public function invoiceItemList($InvoiceId)
{
try
{
$invoiceItemListQuery = $this->PDOconn->prepare(" SELECT * FROM tlabinvoiceitemdetails WHERE RefInvoiceId='".$InvoiceId."' ");
$invoiceItemListQuery->execute();
$invoiceItemList = $invoiceItemListQuery->fetchAll();
return $invoiceItemList;
}
catch(PDOException $e)
{
return $e->getMessage();
}
}
Sure you can get those results with one function, just return them as an array.
BUT as viion pointed out in the comments, why do you even want that?
They dont seem to be related and it makes the code much more readable
if those 2 functions stay seperated.
If you want to merge the functions anyway, here is an attempt on how you would do it.
public function getReferralDoctorDataAndInvoiceItemList($ReferredByIdUser)
{
$returnArray = array();
try
{
$referralDoctorDataQuery = $this->PDOconn->prepare("
SELECT * FROM tuserlist AS a
LEFT JOIN tdoctorprofilelist AS b
ON a.IdUser = b.RefIdUser
WHERE
a.IdUser = $ReferredByIdUser
");
$referralDoctorDataQuery->execute();
$referralDoctorData = $referralDoctorDataQuery->fetch();
$returnArray['referralDoctorData'] = $referralDoctorData;
}
catch(PDOException $e)
{
return $e->getMessage();
}
try
{
$invoiceItemListQuery = $this->PDOconn->prepare(" SELECT * FROM tlabinvoiceitemdetails WHERE RefInvoiceId='".$InvoiceId."' ");
$invoiceItemListQuery->execute();
$invoiceItemList = $invoiceItemListQuery->fetchAll();
$returnArray['invoiceItemList'] = $invoiceItemList;
}
catch(PDOException $e)
{
return $e->getMessage();
}
return $returnArray;
}
In my code I did not correct your usage of PDO (since I havent ever
used PDO myself) but as I understand PDO it should be used like
Jokatek mentioned in his answer.
You should not try to do two different things with one function. If you have two queries with different results you should also use different functions, but if you want only one function, you should try to encapsulate your functions with a facade class.
But you should also use PDO in the right way, for example your first statement.
$referralDoctorDataQuery = $this->PDOconn->prepare(
'SELECT * FROM tuserlist AS a
LEFT JOIN tdoctorprofilelist AS b
ON a.IdUser = b.RefIdUser
WHERE
a.IdUser = :userId'
);
$referralDoctorDataQuery->execute(array('userId' => $ReferredByIdUser));

The lifecycle of an object in PHP

I have two PHP scripts that I included below. Both of them attempt to do the same thing, but one works and one does not. I'm looking for someone to explain what PHP is doing under the covers. I'm new to PHP and I suspect that my Java experience is poisoning my thought process when I work in PHP.
What I'm attempting to do is functionally very simple -- Insert a question into a mySQL database table, retrieve the primary key of the inserted row, and then insert five answers into another table with a foreign key relationship to the question.
My original logic looked like this:
ManageQuestions.php:
<?php
session_start();
include('query.php');
echo "begin <br>";
if (isset($_POST['submit'])) {
echo "manageQuestion <br>";
$query = new Query;
$query->createTransaction();
$query->executeCreateUpdateDelete("INSERT INTO question (question) VALUES ('".$_POST['question']."'); ");
$question_pid = $query->getLastInsertedId();
$query->commitTransaction(); // Need to figure out how to do dirty reads so I can remove this.
echo $question_pid."<br>";
$result = $query->executeRead("SELECT question_pid FROM question where question_pid = '".$question_pid."';");
echo count($result)."<br>";
//if (count($result) === 1) {
$query->createTransaction(); // Need to figure out how to do dirty reads so I can remove this.
foreach($_POST['answer'] as $answer) {
$correctAnswers = 0;
$query->executeCreateUpdateDelete("INSERT INTO answer (question_fid, answer, isCorrect) VALUES ('".$question_pid."','".$answer['answer']."','".$answer['isCorrect']."')");
if ($answer['isCorrect'] === 1) {
$correctAnswers = $correctAnaswers + 1;
if ($correctAnswers > 1){
echo "Failed to insert answers";
$query->rollBackTransaction();
break;
}
}
}
echo "Success";
$query->commitTransaction();
/* } else {
echo "Failed to insert question";
$query->rollBackTransaction();
} */
}
?>
Query.php:
<?php
session_start();
class Query
{
private $host="<censored>";
private $username="<censored>";
private $password="<censored>";
private $db_name="<censored>";
private $pdo;
private $pdo_statement;
private $pdo_exception;
public function executeCreateUpdateDelete($pQuery)
{
$this->pdo_statement = $this->pdo->prepare($pQuery);
return $this->pdo_statement->execute();
}
public function executeRead($pQuery)
{
try
{
$dbh = new PDO("mysql:host=$this->host;dbname=$this->db_name", $this->username, $this->password);
$result = $dbh->query($pQuery);
$dbh = null;
return $result->fetchAll();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function createTransaction()
{
$this->pdo = new PDO("mysql:host=$this->host;dbname=$this->db_name", $this->username, $this->password);
$this->pdo->beginTransaction();
}
public function commitTransaction()
{
$this->pdo->commit();
}
public function rollBackTransaction()
{
$this->pdo->rollBack();
}
public function getLastInsertedId()
{
$this->pdo->lastInsertId();
}
}
?>
When I rewrote my logic to not use a separate query class, I was able to do what I wanted to do. The only thing I've been able to find online about the life cycle of a PHP object is that it begins at the start of a script and ends at the end of a script. Does that imply that my query object is instantiated every time I call one of its methods and garbage collected when that particular method ends? Moving the logic out of that class and into the script caused my logic to work. This is what it looks like now:
ManageQuestions.php:
<?php
session_start();
include('query.php');
echo "Begin <br>";
if (isset($_POST['submit'])) {
echo "manageQuestion <br>";
$host="<censored>";
$username="<censored>";
$password="<censored>";
$db_name="<censored>";
$pdo = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
$stmt = $pdo->prepare("INSERT INTO question (question) VALUES ('".$_POST['question']."'); ");
$stmt->execute();
$question_pid = $pdo->lastInsertId();
echo $question_pid."<br>";
$stmt = $pdo->query("SELECT question_pid FROM question where question_pid = '".$question_pid."';");
$result = $stmt->fetchAll();
echo count($result)."<br>";
foreach($_POST['answer'] as $answer) {
$correctAnswers = 0;
$stmt = $pdo->prepare("INSERT INTO answer (question_fid, answer, isCorrect) VALUES ('".$question_pid."','".$answer['answer']."','".$answer['isCorrect']."')");
$stmt->execute();
}
echo "Success";
}
?>
Even though this fixed my issue, I don't understand why. If someone could explain that, I would be extremely grateful.
Cheers!
Does that imply that my query object is instantiated every time I call one of its methods and garbage collected when that particular method ends?
No. It's per request, not per method call. So the query object is instantiated every time the script is called and it gets unset (and not necessarily garbage collected) when the script ends.
However you could better manage the resource of the PDO object inside your Query class because you create a new instance (which would mean that it connects again to the database server which is not that cheap). So some lazy loading does not seem bad:
class Query
{
...
/** #var PDO */
private $pdo;
...
private function getPdo() {
if (!$this->pdo) {
$this->pdo = new PDO("mysql:host=$this->host;dbname=$this->db_name", $this->username, $this->password);
}
return $this->pdo;
}
public function executeRead($pQuery)
{
try {
$dbh = $this->getPdo();
$result = $dbh->query($pQuery);
return $result->fetchAll();
} catch (PDOException $e) {
echo $e->getMessage();
}
}
public function createTransaction()
{
$this->getPdo()->beginTransaction();
}
...

Retrieving list of items using php

I am trying to retrieve a list of items from a mySQL db and insert them as a list in a select object on a webpage. The following is the bit of code that isnt working.
In the first line, I am trying to retrieve a JSON object from a public function called getBrands() in a singleton object I have created called DatabaseInterface.
The second line is then attempting to turn that JSON object into a php array.
Finally, I am running a loop which can option each item in between tags for the webpage.
Where am I going wrong?
<?php
var $brandArrayJSON = DatabaseInterface::getBrands();
$brandArray = JSON_decode($brandArrayJSON);
for ($loop=0; $loop < sizeof($brandArray); $loop++) {
echo "<option>$brandArray[$loop]</option>";
}
?>
EDIT: In case it helps, here is my DatabaseInterface singleton. I have included this file at the top of my php file
class databaseInterface {
private static $_instance;
// Private constructor prevents instantiation
private function __construct() {
}
public static function getInstance() {
if (!self::$_instance) {
self::$_instance = mysqli_connect(self::databaseHost, self::databaseUsername, self::databasePassword, self::databaseName);
if (mysqli_connect_errno(self::$_instance)) {
throw new Exception("Failed to connect to MySQL:" . mysqli_connect_error());
}
}
return self::$_instance;
}
public function getBrands() {
try {
$con = DatabaseInterface::getInstance();
} catch (Exception $e) {
// Handle exception
echo $e->getMessage();
}
$query = "SELECT psBrandName from brands";
$result = mysqli_query($con, $query) or die ("Couldn't execute query. ".mysqli_error($con));
$resultArray[] = array();
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
$resultArray[] = $psBrandName;
}
return json_Encode($resultArray);
}
There is nothing "wrong" with the code, in that it should work (provided nothing is broken on the query-side). However, there are several things that should be improved.
First, basically what the getBrands() method is doing is equivalent to this:
$brandArray = json_encode(array('test','test2','test3'));
echo $brandArray; // returns ["test","test2","test3"]
Now, when you decode that you get the same thing you originally put in (an array):
$brandArray = json_decode('["test","test2","test3"]');
var_dump($brandArray); // Will dump an array
Since this is an array (not a PHP object), you can just use a foreach.
foreach($brandArray as $option) {
echo '<option>', $option, '</option>';
}
If you're worried about it being an object in some instances (maybe you had a non-array JS object which would be mostly the equivalent to a PHP associative array), you could cast the json_decode result into an array.
$brandArray = (array)$brandArray;
Now, in your getBrands() method, I would highly recommend just using $row['psBrandName'] instead of cluttering things up with extract, unless you have a really good reason to do this.

Right mvc concept, little php code in view

I have one not understood point In MVC pattern. Please help understood.
for example we have table for cars in database, we want obtain and print results from table, but if results are not found (0 rows), in this case print: "We dont have results"
this is models.php
class modesl {
function getCars () {
$res = $this->db->query("SELECT names FROM cars");
if ($res->num_rows == 0) {
return "We dont have results";
}
else {
return $res;
}
}
}
this is views.php
class views {
function loadHTML ($resultFromCars) {
require 'carspage.php';
}
}
this is carspage.php
<html>
<body>
<?php
if (is_object($resultFromCars)) {
while ($row = $resultFromCars->fetch_assoc()) {
echo $row['names']."<br>";
}
}
else {
echo $resultFromCars;
}
?>
</body>
</html>
this is controllers.php
class controllers {
function generatePage () {
$model = new models();
$resultFromCars = $model->getCars();
$view = new views();
$view->loadHTML($resultFromCars);
}
}
This works, but as I know, many php code in view, (that is condition if (is_object) { } else { } ) is not right MVC. tell please for this concret case, what must be change in my architecture (lol), for obtain right MVC concept?
I like the answer provided by Havelock.
I would adjust this even further, by making sure your model already returns the data in an array format (or false, if nothing is found). Therefore, the logic for extracting data from resultset stays in the model, where it really should be.
Your view becomes even simpler then:
<?php
if (!empty($results)) {
foreach ($results as $row) {
echo $row['name'] . "<br />";
}
} else {
echo "Eh, Nothing found...";
}
You seem to have done a good job, just one small thing to improve. As the model is a wrapper for data only, so you should return only data (and no strings, containing error/exception messages). In the case there's no data to return, then return FALSE, as it's done in PHP.
class CarModel {
function getCars () {
$res = $this->db->query("SELECT names FROM cars");
if ($res->num_rows == 0) {
return FALSE; // if that happens, the function will stop execution here, so no "else" is needed
}
return $res;
}
}
And in your view
<?php
if ($resultFromCars === FALSE && !empty($resultFromCars)) {
echo "We don't have results";
}
else { // now you know it's not FALSE, so it must be an object, no need to check whether it is one
while ($row = $resultFromCars->fetch_assoc()) {
echo $row['names']."<br>";
}
}
?>

processing mysql assoc results through various classes

Hi I've recently started yet another project and my boss is insisting that we use the MVC model, the problem being that due to many articles showing different ways to do this we havent managed to agree on what a proper MVC model should look like.
So here's my problem for this project (whether this is the correct way to do it or not) I am using the following baseline rules
Controller classes manage both getting the data from the model classes and passing the data to the view classes and retrieving the view and displaying it
Model classes managhe all database actions and return the data using mysql_fetch_assoc
View classes create the views using the data etc.
So my issue is with processing the information from mysql_fetch_assoc normally you would do something like this (assuming we have already run a query)
while ($row = mysql_fetch_assoc($result)) {
echo $row["username"];
}
but as I'm processing the results in the view class rather than the model how do I cycle through all of the results when I have already passed the assoc array to the view, currently I'm getting a problem where it keeps looping through the results until it hits a memory size error so for some reason it isn't able to figure out how many results it needs to cycle through
My current code snippets are below sorry for the bad explainations.
Controller
require_once 'admin_model.php';
require_once 'admin_view.php';
class admin_controller {
public $model;
public $view;
public function __construct() {
$this->model = new admin_model;
$this->view = new admin_view;
}
public function get_group_view() {
$in_model = $this->model->get_group_view();
$in_view = $this->view->get_group_view ($in_model);
echo $in_view;
}
Model
class admin_model {
public function get_group_view() {
$query = mysql_query("
SELECT
group_id,
group_name
FROM
user_groups
");
return mysql_fetch_assoc($query);
}
}
View
class admin_view {
public function get_group_view($group_data) {
while($group_data) {
$output .= $group_data['group_id'] . '###' . $group_data['group_name'] . '<hr />';
}
return $output;
}
}
Which currently returns the error:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 133693393 bytes)
So can someone please advise me on the best way to go through the results without moving 'mysql_fetch_assoc' function from the model class?
PS I know I'm probably doing MVC completely wrong but it works for us and we don't want to have to research and change our code yet again thanks.
You should not return the MySQL Result - you should do:
$return = array();
$query = mysql_query("SELECT group_id, group_name FROM user_groups");
while($row = mysql_fetch_assoc($query)) {
$return[] = $row;
}
mysql_free_result($row);
return $return;
And you should fix the $group_data bug per #Roman_S . The correct use, along with the above code is
public function get_group_view($group_data) {
$output = '';
foreach($group_data as $group) {
$output .= $group['group_id'] . '###' . $group['group_name'] . '<hr />';
}
return $output;
}
Finally you should migrate to MySQLi or PDO if possible.
You have en error here
while($group_data) {
$output .= $group_data['group_id'] . '###' . $group_data['group_name'] . '<hr />';
}
If $group_data is not empty - your loop will never end.
To give a suggestion on how to handle database control.
When using PDO for instance
$pdoInst = new PDO( .. );
and we have a method somewhere that validates every statement the $pdoInst produces
abstract class .. {
public static function validateStmt($stmt) {
if($stmt !== false) { .. }
// everything else you like, even error handling, log files, etc.
}
}
}
a prepared statement like the get_group_view method will look like the following
public function get_group_view {
$stmt = $pdoInst->prepare(" .. QUERY .. ");
// the return can be wrapped in a method to handle errors, etc, which can be done
// here or else where.
$stmt->execute() // returns true or false
return $stmt;
}
now for iteration
public function get_group_view($group_data) {
$output = "";
// validate the statement, can be done here or else where as said before
if($pdoInst::validateStmt($group_data)) {
// many ways how to iterate, foreach is just one.
foreach($group_data as $index => $group) {
$output .= $group['group_id'] . '###' . $group['group_name'] . '<hr />';
}
}
return $output;
}
The nicest thing about PDO is that you can extend the classes with custom ones. You can add functionality that adds more value to your Model.

Categories