$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];
}
}
}
Related
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.
I loop trough the rows with this code:
while ($row = $result->fetch_assoc()) {
//...
}
But how is it possible before the mysqli_fetch_assoc to check if there will be a next record, or not? I mean, like: $result->hasNext()
Check the total number of returned rows using $mysqli->num_rows, then compare it to a counter in your loop that you increment with each loop iteration.
$row_cnt = $result->num_rows;
$loop_ct = 0;
while($row = $result->fetch_assoc()) {
if(++$loop_ct < $row_cnt) {
//do something
}
}
I prefer working efficiently and don't write extra code if it isn't needed. The following will work just fine:
$cnt = $result->num_rows;
while($row = $result->fetch_assoc()){
//....
$cnt--;
if($cnt == x){ //Where x is the number you want
//....
}
}
You're doing a while loop until you don't have any rows left, so the question is do you really need a test or do you just run the code you want at the end of your loop? If you need to test inside whether there will be a next row, you could do this:
$row = $result->fetch_assoc();
while (1) {
...
if (!$row = $result->fetch_assoc()) {
// No next row
break;
}
}
Which is pretty similar to what you're doing now.
Consider the code you posted
while ($row = $result->fetch_assoc()) {
//...
}
It is already doing that. check out the docs for mysqli_result::fetch_assoc, the while loop will break if $result->fetch_assoc() returns NULL. You don't need to manually check anything.
Either you can go with #McWayWeb or you can try this function mysqli_next_result().
Read it's manual here:- http://php.net/manual/en/mysqli.next-result.php
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 am making a mysql query . I want to add result to an array. suppose I am selecting all user from user table. I want to get everyones name. if the row=5 i want to save every name according to the row index.
if (mysql_num_rows($query) > 0)
{
$row = mysql_fetch_array($query);
//echo ($row);
$num=mysql_num_rows($query);
echo ($num);
for ($i=1; $i<=$num;$i++){
//here I want to save all name to an array.
}
Please help.
You might be looking for something like this:
$rows = array();
// while there are more records, add them to `$rows`
while($row = mysql_fetch_assoc($result)) {
$rows []= $row;
}
Note that mysql_fetch_assoc() will just return false if there are no (more) records in the result set. So you don't need the call to mysql_num_rows()
$num = mysql_num_rows($query);
if($num > 0)
{
while($row = mysql_fetch_array($query)
{
$names[] = $row['name'];
}
}
That will create an array called $names which you can loop through later. Also, it's a good time to look into mysqli_* functions, or PDO.
Actually I am very new to PHP.
My code goes here:
<?php
$mysql = mysql_connect('localhost','Susi','susi');
mysql_select_db('mydb', $mysql);
$rs = mysql_query("show tables;");
$nonTable = array('table_1','table_2');
while ($tabs = mysql_fetch_assoc($rs)) {
foreach ($tabs as $tables) {
echo $tables.'<br />';
}
}
?>
In this case $rs stores the entire table of the database "mydb" .
There is another array $nontable which contains some tables which are already in Table list of "mydb" database.
I want to pass those table names to the while loop excluding the tables in "$nontable" array.
I tried
array_diff($rs,$nontable)
but it provided NULL result.
I will be very happy if somebody helps me out...
Thanks in advance...
Do you mean:
while ($tabs = mysql_fetch_assoc($rs)) {
foreach ($tabs as $tables) {
if(!in_array($tables, $nonTable)) {
echo $tables."<br />";
}
}
}
Your $rs does not contain any result... It contains the resource id
hence it outputs you NULL for array difference.
Your variable $tabs which you are iterating in while loop, is the
associative array with value
Now if you want those tables names which are NOT in $nontable array
then you have to do this
while ($tabs = mysql_fetch_assoc($rs)) {
foreach ($tabs as $tables) {
if(!in_array($tables, $nonTable)) {
echo $tables."<br />";
}
}
}
You can't do array_diff($rs,$nontable) because $rs is not an array, so you need to do it in such way:
<?php
$mysql = mysql_connect('localhost','Susi','susi');
mysql_select_db('mydb', $mysql);
$rs = mysql_query("show tables;");
$nonTable = array('table_1','table_2');
while ($tabs = mysql_fetch_array($rs)) {
$diff = array_diff($tabs, $nontable)
foreach ($diff as $tables) {
echo $tables.'<br />';
}
}
EDITED: also you need to use mysql_fetch_array instead of mysql_fetch_assoc
As #Sudhir said, you can use in_array() function in PHP. This function search your expected item through an array and will return True if it can find it. So using the code that #Sudhir suggested, will work for you as you want.
To know more about in_array() function, see http://php.net/manual/en/function.in-array.php