PHP - Execute select query and loop through results - php

I am developing a web service using PHP. I am having some trouble while executing the select query. This is the code I'm using.
DB_Functions.php
public function getCompanies() {
$result = mysql_query("SELECT * FROM company");
// check for successful store
if ($result) {
return mysql_fetch_array($result,true);
} else {
return false;
}
}
GetCompanies.php
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$companies = array();
//$rows = $db->getCompanies();
while ($row = $db->getCompanies()) {
echo $row['companyName'];
$rowArr = array();
$rowArr['CompanyName'] = $row['companyName'];
$rowArr['CompanyID'] = $row['companyId'];
//array_push($companies, $rowArr);
$companies[] = $rowArr;
}
header('Content-Type: application/json');
$response=array("Companies"=>$companies);
$json = json_encode($response);
echo $json
?>
But the problem is in GetCompanies.php file the while loop is runs endless. The code appears to be ok. Any help would be appreciated.

When you do while ($row = $db->getCompanies()) { you are running the entire query over again and returning the 1st row each time. mysql_fetch_array returns one row.
What you need to do is have getCompanies() loop over all the rows and return an array.
public function getCompanies() {
$result = mysql_query("SELECT * FROM company");
// check for successful store
if ($result) {
$ret = array();
while($row = mysql_fetch_assoc($result)){
$ret[] = $row;
}
return $ret;
} else {
return false;
}
}
Now, getCompanies() will return you an array that you can just foreach over:
$rows = $db->getCompanies();
foreach($rows as $row){
// ...
}

Change your while loop declaration to something like
foreach($rows as $row) {}
And as Pavlin said, move the function call to getCompanies() outside the loop.
Also, how about modifying the query to select a particular set of fields from the database and directly sending them as the response without doing any additional processing?

Since you are implementing Select query without any condition(where clause). And since the company table has data it would always return true in the while loop this makes the while loop an infinite loop. For while to work properly the condition should become false to exit the loop.
Its not a programming flaw its a logical one.

The php docs have all the information you need. You're using the wrong function:
mysqli_fetch_array — Fetch a result row as an associative, a numeric
array, or both
vs
mysqli_fetch_all — Fetches all result rows as an associative array, a
numeric array, or both
Just change your return statement to
return mysqli_fetch_all($result);
or
return mysqli_fetch_all($result, MYSQLI_ASSOC);
to get an associative array.
And of course, you need to move your getCompanies call outside of the loop.
NOTE
php mysql_* functions have been depricated since version 5.5.* and are going to be removed from the language soon. You should look into mysqli_* or PDO.

Related

how to get db all data using array in php

I create as the following function. how to get all data using this array. when run this function will appear only the first record. but, i want it to appear all the records. what is the error in this code.
public function get_All_Se($stId){
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
$data = $result->fetch_array(MYSQLI_ASSOC);
return $data;
}
public function get_All_Se($stId){
$rows=array();
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
while($data= $result->fetch_assoc()){
$rows[]=$data;
}
return $rows;
}
Run loop over all results and add to some return array.
$rows = array();
while(($row = $result->fetch_array($result))) {
$rows[] = $row;
}
As the documentation of mysqli::fetch_array() explains, it returns only one row (and not an array containing all the rows as you might think).
The function you are looking for is mysqli::fetch_all(). It returns all the rows in an array.
public function get_All_Se($stId)
{
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
return $result->fetch_all(MYSQLI_ASSOC);
}
The code above still has two big issues:
It is open to SQL injection. Use prepared statements to avoid it.
or die() is not the proper way to handle the errors. It looks nice in a tutorial but in production code it is a sign you don't care about how your code works and, by extension, what value it provides to their users. Throw an exception, catch it and handle it (log the error, put some message on screen etc) in the main program.
Try this way...
<?php
// run query
$query = mysql_query("SELECT * FROM <tableName>");
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
// OR just echo the data:
echo $row['<fieldName>']; // etc
}
// debug:
print_r($array); // show all array data
echo $array[0]['<fieldName>'];
?>

Database class and while loop

I have a PHP class for querying the database and taking results. I need to be able to loop through multiple rows, but I can't figure out how I'd do that with my current function. My function is:
$data = mysqli_query($this->connectDB(), $query);
$row = mysqli_fetch_array($data);
return $row;
but there's no way to loop through rows that I've tried that doesn't crash the script. I've also tried return mysqli_fetch_array($data);, but that doesn't work either. Is it possible?
You could use:
while ($row = mysqli_fetch_array($data)) {
$array[] = $row;
}
return $array;
php manual: mysql_fetch_array

loop through the data in PDO

I am having difficult loop through the data in PDO and print the data as long as there it has more data for a specific user. I create a function which performs the select. Here is the code that contain the select function, http://pastebin.com/GiAyCBys. I am trying to use that function in cartexe.php using the following code,
while($row = select($conn, 'user', 'cart', $user,':user','*'))
{
echo 'Hello';
}
but I got stuck in an infinite loop. I am grateful for any help I can get.
The solution is to change select to return all rows , since fetch() only return a single row at the time.
Option 1:
$result = array();
while($row = $smtp->fetch(PDO:: FETCH_ASSOC)){
$result[]=$row;
}
return $result;
option 2:
$result = $smtp->fetchAll(PDO:: FETCH_ASSOC);
return $result;
use your function like this
$rows = select($conn, 'user', 'cart', $user,':user','*');
foreach($rows as $row){
//do something with $row
}

php MySQLi fetch results best practice

These are my two methods for querying a database.
This is my first method that saves all the results in an array. Then i use a foreach loop to loop through the array.
public function query($query) {
$rows = array();
if ($result = $this->mysqli->query($query)) {
if($result->num_rows > 1) {
while ($item = $result->fetch_assoc()) {
$rows[] = $item;
}
//jo else sepse nxjerr error kur ska asnje row i ben fetch kur ska row.
} else if($result->num_rows == 1) {
$rows = $result->fetch_assoc();
}
return $rows;
} else {
echo "error";
}
}
Then to output I use:
$run_query = $db->query($query);
foreach ((array)$runk_query as $data) {
....
This is my second method:
$query = $db->query("SELECT * FROM ...");
while($run_query = mysqli_fetch_array($query)) {
//OUTPUT data.
....
}
I notice that in many cases I need to output the results so I think using the first method is bad because I use once the while loop and then I use again a foreach loop so the work is done twice but the second way is not very OOP.
Can anyone suggest me the best method of this or if possible another better method?
You can likely replace you entire first function with a call to mysqli_fetch_all() instead of iterating through each record with fetch_assoc(). This way you don't have to build your array result by result.
You can then run through all the results with your second foreach as per usual.
See: http://www.php.net//manual/en/mysqli-result.fetch-all.php
Alternatively if you were using PDO you could use fetchAll()
See: http://www.php.net/manual/en/pdostatement.fetchall.php

mysql fetch return only return most recent row in class

I have a MySql class and I fetch the Mysql rows by returning them as a method:
public function fetch_assoc($result_set){
return mysql_fetch_assoc($result_set);
}
For some reason it only return one result when I try to iterate through an method return through the object I have instantiated.
while ($row = $a->fetch_assoc($result_set){
...
}
While doing the old fashion ways works, and gives me all the rows
while($row = mysql_fetch_array($result_set)){
$row['0'];
}
Any ideas?
That is because mysql_fetch_assoc return only one result and moves the pointer to the next. So at each iteration it returns moves the pointer and returns false when it reaches the end of the results.
You can modify your method this way to make it work:
public function fetch_assoc($result_set){
$resultArray = array();
while ($row = mysql_fetch_assoc($result_set){
$resultArray[] = $row;
}
return $resultArray;
}
And you can use the data as so:
foreach ($obj->fetch_assoc($result_set) as $row){
echo $row['stuff'];
}
Note that in this case $obj->fetch_assoc($result_set) returns all the results, and i am just looping through it using a foreach loop;

Categories