i'm new to the php mysql usage. i'm selecting the results from database .. and i'm cycling/printing them out to the screen using while($stmt->fetch()): .. what i'd like to do is to cycle through the results again after the first cycle without calling the database (frombuffered results set).
i'm using php5, mysqli, stms on xampp server.
while($row = $stmt->fetch()){
$storedRows[] = $row;
//do stuff
}
foreach($storedRows as $row){
//do more stuff
}
You can use arrays.
When you cycle through the result for the first time you can put the values in the array and later in the 2nd cycle you can access the elements from the array.
Something like:
$query = "SELECT name FROM EMP";
$arr = array();
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($name);
// 1st cycle.
while ($stmt->fetch()) {
$arr[] = $name; // save in array.
}
$stmt->close();
// 2nd cycle.
foreach($arr as $name) {
// use $name again.
}
}
Related
Here is the code
$exec = "EXEC RPT_TEST_2resultSet";
$resultSet = \DB::select($exec);
SP is returning 3 result sets. But in php it prints first set of result set only. How to fetch the other 2 set of result sets? Tried the solution suggested by others. Was getting some other errors.
Make a foreach
check example:
foreach ($resultSet as $result) {
echo $result['someDataFromResult'];
}
This will repeat for the amount of data is in the $resultSet array
Found the simple solution for this problem.
$pdo = \DB::connection()->getPdo();
$sql = 'EXEC Test_SP_MultiResultSet';
$stmt = $pdo->query($sql);
do {
$rows = $stmt->fetchAll(\PDO::FETCH_NUM); // Keys will be start from zero , one, two
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); // Column names will be assigned for each value
if ($rows) {
$sheetData[] = $rows;
}
} while ($stmt->nextRowset());
Source Link
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;
}
}
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
I have this sample query:
$STH = $DBH->query("SELECT id FROM table");
I want to get the first row and then loop and display all rows. So I use the following to get the first row:
$STH->setFetchMode(PDO::FETCH_ASSOC);
$first_row = $STH->fetch();
$first_row = $first_row['id'];
I use while loop to display all rows again:
while ($list = $STH->fetch()) {
$id = $list['id'];
echo $id;
}
Now the while skips the first row and I want it to be displayed. Is there an equivalent to mysql_data_seek to reset the pointer again to the first row? I know fetchall can be used but it's bad on memory and wasteful. I could also run the query and limit to 1 but this is not recommended as I have a query that joins multiple tables and would be very slow. Is there any other solution?
Thanks
I take that back looks like you can use the cursor orientation contants to select the result... sample code coming... I havent tried this so you may need to play a bit. This is also based on the assumption that a PDO::FETCH_ORI_FIRST acts like a data_seek and leaves the cursor on the first position as opposed to returning it to whatever it was before.
$stmt = $pdo->prepare('SELECT id FROM table', array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
$first = $pdo->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_FIRST);
$first_row = $first['id'];
// other stuff
// first iteration we rewind to the first record;
$cursor = PDO::FETCH_ORI_FIRST;
while (false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC, $cursor))) {
$id = $row['id'];
// successive iterations we hit the "next" record
$cursor = PDO::FETCH_ORI_NEXT;
echo $id;
}
I dont think you can rewind a statement... Assuming these blocks arent seprated by a bunch of intermediary logic id just do it in the loop.
$STH->setFetchMode(PDO::FETCH_COLUMN); // no need to pull an array
$count = 0;
while ($id = $STH->fetch()) {
if($count === 0) {
$first_row = $id;
}
echo $id;
$count++;
}
Could you just use a do...while loop instead?
$STH->setFetchMode(PDO::FETCH_ASSOC);
$list = $STH->fetch();
$first_id = $list['id'];
do {
$id = $list['id'];
echo $id;
} while ($list = $STH->fetch());
You can fetch all the result, and then just act on it as an array. So, for instance, you could shift the first result off the front, and then loop over any additional rows:
<?php
$sql = "YOUR QUERY";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// get first row
$firstRow = array_shift($rows);
// loop over remaining rows
foreach ($rows as $row) {
// do something
}