Iterate array in Object from Class using fetch(PDO::FETCH_ASSOC) - php

I've a class with viewData() method that pull the data from the DB table.
I want to return the data result array in Class and iterate the array in Object
I'm able to make it work with fetchAll() but couldn't figure it out how to return the result with fetch() using while loop.
<?php
class CrudClass{
private $db;
function __construct($DB_con){
$this->db = $DB_con;
}
/* DATA VIEW METHOD */
public function viewData(){
$sql = "SELECT * FROM tbl_users";
$stmt = $this->db->prepare($sql);
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
return $row; // it doesn't work
}
// below code is working
/*if($stmt->rowCount()>0){
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}*/
}
}
// instantiate an Object
$obj = new CrudClass($DB_con);
$rows = $obj->viewData();
foreach($rows as $row) {
echo $row['first_name']. " ". $row['last_name'] ."<br>";
}
?>
The reason I want to do that way, because I don't want to pull the data at one go with fetchAll. Instead want to loop through each row at a time. Any help will be appreciated.

You should return array.
$result = []; // initiate the array
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
return $result[] = $row; // put each row in the result array
}
return $result; // return the result array
Now the whole method will look something like below
/* DATA VIEW METHOD */
public function viewData() {
$sql = "SELECT * FROM tbl_users";
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = []; // initiate the array
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
return $result[] = $row; // put each row in the result array
}
return $result; // return the result array
}
This way you are assured that even if there is no result set, only array will get returned.
If above doesn't work. Try following two solutions.
1.Test explicitly for false.
while(($row = $stmt->fetch(PDO::FETCH_ASSOC) !== false) {
return $result[] = $row; // put each row in the result array
}
2.Use foreach
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
return $result[] = $row; // put each row in the result array
}

It is possible to return something you can use in a foreach without having to preload all the results (i.e. using PDOStatement::fetchAll()) and without returning the PDOStatement itself -- if that's what you are trying to do.
Because PDOStatement implements Traversable you you can construct an IteratorIterator from the PDOStatement and return that.
class CrudClass
{
public function viewData()
{
$sql = "SELECT * FROM tbl_users";
$stmt = $this->db->prepare($sql);
$stmt->execute();
return new \IteratorIterator($stmt);
}
}
// instantiate an Object
$obj = new CrudClass($DB_con);
$rows = $obj->viewData();
foreach($rows as $row) {
echo $row['first_name']. " ". $row['last_name'] ."<br>";
}
Note that if you were try and foreach over $rows more than once, it will error because because the results of a PDOStatement cannot be rewound.

Related

Adding elements from an array to a sql query in PHP

I'm trying to put an array with values returned from a function to a sql query in PHP. Looking for information on how to do this, I tried to change the format of the array with the parameters fetch_assoc and fetch array, but it didn't help. I also tried to do a foreach loop for this array and execute sql with each iteration, but it also didn't do anything. How can I do this ?
This is my function which returns me an array of values:
public static function getLilanteProductCategoryForEmpik() {
$returnedArray = [];
$pdo = PDOConnector::getConnection();
echo $query = "SELECT product_type FROM `shopifyProductsLilante`
INNER JOIN offers_import_error_report_3839_14794292
WHERE shopifyProductsLilante.sku=offers_import_error_report_3839_14794292.sku";
$stmt = $pdo->prepare($query);
$stmt->execute( );
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$returnedArray[] = $row;
}
var_dump($returnedArray);
return $returnedArray;
}
and this is the function where I want to put the values from the array in the sql query:
public static function getEmpikCategoryToCSVFile() {
$returnedArray = [];
$lilanteProductCategory = MysqlProvider::getLilanteProductCategoryForEmpik();
$pdo = PDOConnector::getConnection();
foreach($lilanteProductCategory as $lilanteCategory)
{
echo $query = "SELECT empik_category FROM `empik_categories` INNER JOIN shopifyProductsLilante
WHERE $lilanteCategory=empik_categories.lilante_category";
}
$stmt = $pdo->prepare($query);
$stmt->execute( );
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$returnedArray[] = $row;
}
print_r($returnedArray);
return $returnedArray;
}

PHP Sql, returns one row

I have the following code that calls a DB function that retrieves all rows from a table and then echo's them in JSON.
$key = $db->getKeyPermissions();
if ($key != false) {
// use is found
$response["error"] = FALSE;
$response["key"]["endpoint_name"] = $key["endpoint_name"];
$response["key"]["live"] = $key["live"];
$response["key"]["activity_name"] = $key["activity_name"];
echo json_encode($response);
} else {
This is the DB function
public function getKeyPermissions()
{
$stmt = $this->conn->prepare("SELECT * FROM key_permissions WHERE 1");
if ($stmt->execute()) {
$key = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $key;
} else {
return NULL;
}
}
This all works fine except that it only returns the first row and then stops. Read that you have to loop the fetch_assoc() but I couldn't get this working. I would like all rows to be pushed into $key and returned, but all attempts result in an array conversion and non-object errors. Can somebody help me along the way?
EDIT:
public function getKeyPermissions()
{
$stmt = $this->conn->prepare("SELECT * FROM key_permissions WHERE 1");
if ($stmt->execute()) {
$key = array();
while($row = $stmt->get_result()->fetch_assoc()) { //Call to a member function fetch_assoc() on a non-object
$key .= $row; // Array to string conversion
}
$stmt->close();
return $key;
} else {
return NULL;
}
}
You want to call get_result exactly once, and fetch_assoc as long as there are rows:
$result = $stmt->get_result();
$key = array();
while ($row = $result->fetch_assoc()) {
$key[] = $row;
}
return $key;

Fatal error: Call to a member function fetch_assoc() on a non-object while converting result to array

I am trying to fetch multiple rows in form of an array and then converting it to json
Heres my code :
public function getTest($standard,$chapid,$count)
{
if($count>0)
{
$stmt = $this->conn->prepare("SELECT question from questions where standard=? and chapterId=? ORDER BY rand()");
$stmt->bind_param("ss", $standard,$chapid);
$result=$stmt->execute();
echo $result;
$stmt->close();
$rows = $this->resultToArray($result);
echo json_encode($rows);// Array of rows
}
else
{
$rows["success"] = 0;
$rows["message"] = "Posts NOT Available!";
}
echo json_encode($rows);
}
public function resultToArray($result) {
$rows["success"] = 1;
$rows["message"] = "Post Available!";
$rows["posts"] = array();
while($row = $result->fetch_assoc()) // <--Getting ERROR OVER HERE
{
array_push($rows["posts"], $row);
}
return $rows;
}
I am new to php so I can't figure out why I am getting an error in resultToArray() function on while line.
You need to fetch the results of your query; fetch(PDO::FETCH_ASSOC) will return each result as an associative array:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
array_push($results, $row);
}
Your $result passed to your function resultToArray() is in fact a bool. You are passing the wrong variable.

SELECT RECORDS INTO ARRAY

I'm neubie with PHP. I need to build some Web Service so, I have problems.. please help me.
I have this code, I have to put in array the Select's records and the return in JSON.
The CODE...
function redeem() {
// Check for required parameters
if (isset($_POST["id_cliente"]) && isset($_POST["id_sucursal"])) {
// Put parameters into local variables
$cliente = $_POST["id_cliente"];
$sucursal = $_POST["id_sucursal"];
$stmt = $this->db->prepare('SELECT id_arbitro FROM arbitro WHERE id_cliente =? AND id_sucursal =?') or die(mysqli_error($this->db));
$stmt->bind_param("ii", $cliente, $sucursal);
$stmt->execute();
//$stmt->bind_result($id_arbitro);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$cuantos = count($result);
echo "$cuantos";
$registros = 0;
/*while ($stmt->fetch()) {
$registros ++;
// Return unlock code, encoded with JSON
$result = array("id_arbitro" => $stmt,);
echo "$id_arbitro !";
}
*/
$stmt->close();
if ($registros < 0) {
sendResponse(400,"No existen arbitros con los parĂ¡metros recibidos");
return false;
}
//echo json_encode($result);
sendResponse(200, "FIN");
//printf("ERROR %s",$registros);
return true;
}
sendResponse(400, 'Invalid request');
return false;
}
To encode the results of your query, use something like that
$statement=$pdo->prepare("SELECT * FROM table");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
Based on your comment, you're having trouble understanding how to put them all into an array.
First, make sure that whatever you use for database calls doesn't already have a fetchAll style function that could do this for you.
If you still need to do, you need to define an array first and then add to it:
$results = array();
while ($record = $stmt->fetch()) {
$registros ++;
$results[] = $record;
}
print json_encode($results);
The syntax might vary slightly for your database class but this gives you an idea.

Returning all rows, not just one

I am attempting to return all of the rows in a MySQL table. I have the following function:
function listTickets() {
global $con;
$result = mysqli_query($con, "SELECT * FROM tickets");
while($row = mysqli_fetch_array($result)) {
return array($row['subject'], $row['category'], $row['username'], $row['last'], $row['id', $row['status']);
}
mysqli_close($con);
}
However, print_r(listTickets()) does not return all rows, only the first row. How can I make it so that it will return every row? I know how to do it without using functions and whatnot, but I'd like to figure out how to do it with the function. Thanks!
When you use 'return', your function will return immediately - the first time round the loop. Subsequent runs through the loop are cancelled, as is the mysqli_close.
Also: (1) you are closing the database connection for everyone else (as a rule of thumb, if you open it, close it; if you don't open it, don't close it), and (2) $result isn't the finale result - consider using a more descriptive variable
So then it looks like this:
function listTickets()
{
global $con;
$query = mysqli_query($con, "SELECT * FROM tickets");
$result = array();
while($row = mysqli_fetch_array($query))
{
array_push($result,array($row['subject'], $row['category'], $row['username'], $row['last'], $row['id', $row['status']));
}
return $result;
}
Next, I would add the option MYSQLI_NUM (or even MYSQLI_ASSOC) to mysqli_fetch_array, and remove the code which takes an array, and converts it into almost exactly the same array.
function listTickets()
{
global $con;
$query = mysqli_query($con, "SELECT * FROM tickets");
$result = array();
while($row = mysqli_fetch_array($query,MYSQLI_NUM))
{
array_push($result,$row);
}
return $result;
}
once you use return in a function, the function is ended and the value after return is returned.
Therefore, you need to store your database row somewhere and then at the end return all stored rows.
e.g.:
function listTickets()
{
global $con;
$result = mysqli_query($con, "SELECT * FROM tickets");
$stack = array(); // <- the temp array
while($row = mysqli_fetch_array($result))
{
// push the db result to the stack
array_push($stack, $row);
}
mysqli_close($con);
return $stack;
}
Once a return statement is reached, the function is completed. You will need to gather the rows into some sort of collection and return the collection of rows.
Hope this helps
return exits the function immediately. Accumulate the output in the buffer then return it:
function listTickets()
{
global $con;
$result = mysqli_query($con, "SELECT * FROM tickets");
buffer = array();
while($row = mysqli_fetch_array($result))
{
array_merge(buffer,array($row['subject'], $row['category'], $row['username'], $row['last'], $row['id', $row['status']));
}
mysqli_close($con);
return buffer;
}

Categories