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
Related
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
$result = mysql_query($strSql);
foreach($bestmatch_array as $restaurant)
{
while($row = mysql_fetch_array($result))
{
if($restaurant == $row[0])
{
$value = $row[1];
}
}
}
What I am trying to do is sort the result of array formed by query according to the values stored in $bestmatch array.
I don't know what I am doing wrong but the 4th line just seems to run once. Please help guys. Thanx in advance.
php mysql_fetch_array() not working as expected
Your expectation is not right.
foreach($bestmatch_array as $restaurant)
{
// This loop will only run for first iteration of your foreach.
while($row = mysql_fetch_array($result))
{
}
// everything has been fetched by now.
}
That is a logically incorrect sequence.
You expect your inner loop to be called over and over again as many times as you have the outer loop run but record fetch does not work like that. For outer loop's first run all the rows in $result will be fetched and since you do not reset the counter after your while loop that means after the first run there will be no more rows for the next run.
Solution? Fetch the row from mysql first then use a simple in_array call to check whether that restaurant is there in your array.
$result = mysql_query($strSql);
while($row = mysql_fetch_array($result))
{
$name=$row[0];
if(in_array($name,$bestmatch_array))
$value=$name;
}
Store the results of the query in the array first:
$result = mysql_query($strSql);
$results_row = array();
while($row = mysql_fetch_array($result))
{
$results_row[] = array($row[0],$row[1]);
}
foreach($bestmatch_array as $restaurant)
{
foreach ($results_row as $key => $value)
{
if($restaurant == $results_row[$key][0])
{
$value = $results_row[$key][1];
}
}
}
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.
I'm doing sth like this:
$q3 = $conn3->prepare("SELECT...");
$q3->bindParam(':param1', $param1);
$q3->execute();
$check3 = $q3->fetchAll(PDO::FETCH_ASSOC);
if (!empty($check3)){
$arr = array();
while($row = $q3->fetch(PDO::FETCH_ASSOC)) {
$arr[] = $row;
}
}
but I don't see the data in arr[] later on. What exactly am I doing wrong here? Is there a better way to fetch the data from mysql to an array in php?
fetch() returns the next row in the set. fetchAll() will fetch all the (remaining) rows and move the pointer to the last row, therefore fetch() after fetchAll() will not return anything because there will not be a next row in the set.
You need one or the other. To take advantage of fetchAll you could do:
$check3 = $q3->fetchAll(PDO::FETCH_ASSOC);
foreach ($check3 as $row) {
}
or just use fetch without fetchAll:
while ($row = $q3->fetch(PDO::FETCH_ASSOC)) {
}
Your code, as is, makes the fetch() useless. You could just do:
$arr = $q3->fetchAll(PDO::FETCH_ASSOC);
Which is equivalent to:
$arr = array();
while($row = $q3->fetch(PDO::FETCH_ASSOC)) {
$arr[] = $row;
}
}
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
}