Two MySQL while loops not working properly [PHP] - php

I have two while loops, both through MySQL results, see code:
$result1 = $sql->runQuery1();
$result2 = $sql->runQuery2();
while($record1 = mysqli_fetch_array($result1))
{
echo "$record1['id'] : ";
while($record2 = mysqli_fetch_array($result2))
{
echo "$record2['id'] <br> ";
}
}
Above code will run inside loop only once, code below:
$result1 = $sql->runQuery1();
while($record1 = mysqli_fetch_array($result1))
{
$result2 = $sql->runQuery2();
echo "$record1['id'] : ";
while($record2 = mysqli_fetch_array($result2))
{
echo "$record2['id'] <br> ";
}
}
above will run internal loop as many times as many records is in MySQL query. Is there more efficient way of looping through that data? I don't want to re-run query each time.

If you fetch your result in an array, you should get all results. I suggest for PHP using $results = $sql->runQuery1() which will let you iterate through your results in a loop:
foreach($results as $var) {
$var->doStuff(); // or display or whatever
}
you can of course nest these
foreach($results as $var) {
foreach($results2 as $var2) {
$var->doStuff($var2); //for example
}
}
Here's the manual: http://php.net/manual/de/control-structures.foreach.php
The fetch_array and fetch_assoc will give you all fields in a row from your query into an associative array.

Related

How can I get this php to return the entire column of an sql db

I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}

Storing db value into php array and then looping through the array

What would the benefits be of storing db values into an array and then looping through the array vs just using a while loop?
Outputting db results to an array:
$records = array();
if($results = $db->query("SELECT name, address FROM town")) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row;
}
$results->free();
}
}
Loop through array:
foreach($records as $r) {
$r->name;
}
VS a simple While loop:
if($result = $db->query("SELECT name, address FROM town")) {
if($count = $result->num_rows) {
while($row = $result->fetch_object()) {
echo $row->name, ' ', $row->address, '<br />';
}
$result->free();
}
}
Just a while loop and printing the result is easy and fast, but in certain times you want to do more then just print the array and then it becomes handy if you already work with arrays.
The most common use for this is freeing the resultset, allowing you to perform other db queries (updates, inserts...) before actually making any use of the results you got in the first place.

php mysql_fetch_array() not working as expected

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

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

How do you save rows to an array and print out in PHP using ODBC?

I have the following:
while($myRow = odbc_fetch_array( $result )){ <--lots of rows
$thisResult['name'] = $myRow["name"] ;
$thisResult['race'] = $myRow["race"] ;
$thisResult['sex'] = $myRow["sex"];
$thisResult['dob'] = $myRow["dob"];
}
I can't figure out how to print this back out.
I want to get each row and iterate through each row in the array like a datareader. I'm not sure what to do. I do not want to do the echo in the while. I need to be able to print it out elsewhere. But I don't think I've done it right here to be able to print it later.
I also tried, this, however:
while($myRow = odbc_fetch_array( $result )){ <--lots of rows
print($thisResult[$myRow["name"]] = $myRow);
}
I then tried:
while($myRow = odbc_fetch_array( $result )){ <--lots of rows
print (odbc_result($myRow,"name"));
}
but got an error.
Thank you for any help.
EDIT: when I do this:
while($myRow = odbc_fetch_array( $result )){
print ($myRow["name"]);
}
I get undefined index name. I am mainly concerned with saving to an array but I have to be able to do it in the loop first.
Declare an array before and assign the values to it:
$rows = array();
while($myRow = odbc_fetch_array( $result )){ <--lots of rows
$rows[] = $myRow;
}
Then you can print it e.g. this way:
foreach($rows as $row) {
foreach($row as $key => $value) {
echo $key . ': '. $value;
}
}
or however you want to.
You don't have to access and assign $thisResult['name'] = $myRow["name"] in your while loop as $myRow already is an array. You just copy the values which is unnecessary.
You say you have a lot of rows. Depending of what you really want to do with data, it might be better to put all this functionality into the while loop to avoid creating an array.
How about something like:
$output = '';
while($myRow = odbc_fetch_array( $result )) {
$output = $output."Your name is {$myRow["name"]} and your race is {$myRow["race"]}\n";
}
// print output later...

Categories