Returning all rows, not just one - php

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

Related

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

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.

magento database sql not working

So do not have an idea why this function is not working? i am trying to select all the ids from the table but nothing is selected.
public function jobsArray()
{
$connection = Mage::getSingleton('core/resource')->getConnection('Envato_CustomConfig_Job');
$result = $connection->fetchAll("SELECT id FROM Envato_CustomConfig_Job");
$rows = array();
foreach($result as $record) {
$rows = ('value'=>$record, 'label'=>$record);
}
return $rows;
}
this function below works fine, I need the function above to do the same as teh function below.
public function toOptionArray()
{
return array(
array('value'=>1, 'label'=>'one'),
array('value'=>2, 'label'=>'Two'),
array('value'=>3, 'label'=>'Three'),
array('value'=>4, 'label'=>'Four')
);
}
There are a couple of issues with your code:
You're only selecting a single item (id, but later, I assume you're expecting an ID and a value).
$result = $connection->fetchAll("SELECT id FROM Envato_CustomConfig_Job");
record is an array from your SQL query, so you should be treating it as such. eg. $record['id']
$rows you want as an array, but you're overwriting it each time, so $rows[] = makes more sense
Something like:
public function jobsArray()
{
$connection = Mage::getSingleton('core/resource')->getConnection('Envato_CustomConfig_Job');
$result = $connection->fetchAll("SELECT id, label FROM Envato_CustomConfig_Job");
$rows = array();
foreach($result as $record) {
$rows[] = array('value'=>$record['id'], 'label'=>$record['label']);
}
return $rows;
}
Try using the core read/write resource. Change
$connection = Mage::getSingleton('core/resource')->getConnection('Envato_CustomConfig_Job');
To
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');

PHP OOP: Function not return all row in database to php

I've created a function that suppose to return all row in database to browser, but it is return only one value. Below is my table:
And this is my code:
SqlDatabase.php Classes:
public function query($sql){
$result = mysqli_query($this->connection, $sql);
return $result;
}
test.php:
$database = new SqlDatabase;
//testing function
public static function find_comments($photo_id=0){
global $database;
$sql = "select * from comments";
$sql .= " where photograph_id = {$photo_id}";
$sql .= " order by created ASC";
print_r(self::sql_find($sql));
}
// This is a testing function
public static function sql_find($sql){
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_assoc($result_set)){
$object_array = $row['author'];
} return $object_array;
}
When i try to run this function, It is only return one last value "vai het loc" to PHP:
Comments::find_comments(77);
I tried several ways and do researchs but haven't found any solutions yet. Not sure what am i missing. Need some guide to fetch all row in photograph_id not only one value.
Thanks for helps.
You're overwriting the value, not appending it to the array.
Change this line:
$object_array = $row['author'];
to this:
$object_array[] = $row['author'];
In your sql_find() function and you should get the object.

unable to read value written in mysql database using php using a php function, just after the function is called

In a php function, i tried to insert a row in a database table as
function abnc()
{
$link = conn to db;
$query = "insert into table( a,c ,v) values (1,2,3);"
$result = mysqli_query($link, $query);
if(mysqli_rows_affected($link) == 1){
close conn;
return true;}
else{
return false;
close conn;
}
now, at other place, i called this function, and tried to read the values i had inserted
as
$done = abnc();
if($done)
{
$query = "select * from table where a=1 and c=2 and v=3";
$result = mysqli_query($link, $query);
echo "true";
echo mysqli_num_rows($result);
}
else
{
echo 'false';
}
the output i get is true0;
I think while the function was executing, the script just continued.
I want it to wait until function execution is finished.
Any solution ??
The script does not continue. When you call abnc() that function will be executed and return a value which you store in the variable $done. This value is presumably true since your output is true0.
In abnc() you insert a row. Which means that one row was affected and the function returns true. And you close the db connection, which might be why you cant access your inserted data later.
try this
$done = abnc();
$link = conn to db;
if ($done) {
$query = "select * from table where a=1 and c=2 and v=3";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
do {
$resultSet = array();
if (($row = mysqli_store_result($link))) {
while ($row = mysqli_fetch_assoc($row)) {
$resultSet[] = $row;
}
$return[] = $resultSet;
#mysqli_free_result($row);
}
} while (#mysqli_next_result($link));
return $return;
}
} else {
return false;
}
You closed the database connection in your function try opening it outside the function and closing at the end of your script.

PHP: letting your own function work with a while loop

$qVraagGroepenOp = "SELECT * FROM $tabele WHERE $where";
$rVraagGroepenOp = mysql_query ( $qVraagGroepenOp );
$aVraagGroepenOp = mysql_fetch_assoc ( $rVraagGroepenOp )
and I converted that to a function
vraagOp("testtable","testtable_ID = $id");
function vraagOp($table,$where)
{
$qVraagOp = "SELECT * FROM $table WHERE $where";
$rVraagOp = mysql_query( $qVraagOp );
$aVraagOp = mysql_fetch_assoc( $rVraagOp );
return $aVraagOp;
}
only the problem is when i need more then one row i need to use a while loop
$qVraagGroepenOp = "SELECT * FROM testtable where testtype = test";
$rVraagGroepenOp = mysql_query ( $qVraagGroepenOp );
while ( $aVraagGroepenOp = mysql_fetch_assoc ( $rVraagGroepenOp ) )
{
echo "testing <br>";
}
It wont work anymore is there a trick to make my function work with this while loop?
This won't work but I want to reach to something like it
while (vraagOp("testtable","testtype = test"))
{
echo "testing <br>";
}
Is this possible?
This could be done with static variables in the function scope.
function vraagOp($table,$where)
{
static $rVraagOp;
if(!$rVraagOp){
$qVraagOp = "SELECT * FROM $table WHERE $where";
$rVraagOp = mysql_query( $qVraagOp );
}
return mysql_fetch_assoc( $rVraagOp );
}
That should do what you're after.
This function returns an array of rows - it's a generic pattern yu can use almost anywhere you get multiple rows from a query.
function vraagOp($table,$where)
{
$sql= "SELECT * FROM $table WHERE $where";
$query= mysql_query($sql);
if ($query != false)
{
$result = array();
while ( $row = mysql_fetch_assoc($query) )
$result[] = $row;
return $result;
}
return $false;
}
//usage
$rows = vraagOp($table,$where);
if ($rows)
{
foreach ($rows as $row)
use($row);
}
This function will 'cache' the mysql result resource from each unique $table/$where combination, and fetch the next result from it on each subsequent call. It will return an associative array for each row, or false when there are no rows left.
function vraagOp($table, $where)
{
// Holds our mysql resources in a map of "{$table}_{$where}" => resource
static $results = array();
$key = $table . '_' . $where;
if (!isset($results[$key]))
{
// first call of this particular table/where
$results[$key] = mysql_query("SELECT * FROM $table WHERE $where");
}
$row = mysql_fetch_assoc($results[$key]);
if ($row === false)
// remove this key so a subsequent call will start over with a new query
unset($results[$key]);
return $row;
}
// Usage
while ($row = vraagOp("table1", "where field > 7")) {
print_r($row);
}
This
while (vraagOp("testtable","testtype = test"))
{
echo "testing <br>";
}
will work if you change VraagOp() to return false when no matching record was found.
You would have to move the mysql_query() part out of VraagOp(), and just leave the mysql_fetch_assoc part in.
However, I can't really see what benefit there would be? You would just be building a (unnecessary) wrapper around mysql_fetch_assoc(), wouldn't you?
You'll need to turn vraagOp() into an iterator and then use foreach() in order to make this work.
Your example won’t work because the condition is executed on every iteration. That means vraagOp("testtable","testtype = test") would be called with each iteration until it returns a falsely value. mysql_fetch_assoc does that but your function doesn’t.
How can we call function inside while loop example is below :
$sql_gpfsF="SELECT * FROM emp_salary";
$result_gpfsF=mysql_query($sql_gpfsF);
while($row_gpfsF=mysql_fetch_assoc($result_gpfsF))
{
call_function();
}
function call_function()
{
echo " Function Called </ br>";
}

Categories