Jump to content

[SOLVED] MySQL result printing in for-loop


OnlyLeif

Recommended Posts

I have a script that count and print every week in a selected year.

 

Now i want to connect this to the returned result from a MySQL query.

 

Code to explain what I am trying to accomplish:

 

 

// $number_weeks = weeks in chosen year

for($i = 1;$i <= $number_weeks;$i++)
{
$row = mysql_fetch_array($result);
if ($row['week'] == $i)
  {
    echo "Exsisting in database!";
  }
}

Link to comment
https://forums.phpfreaks.com/topic/61510-solved-mysql-result-printing-in-for-loop/
Share on other sites

OK - I can see a few uses for this kind of iteration - the best solution for you depends on what you are actually going to output info - but lets go on the basis you just want to show if the week is in the database...

 

first you need the query result in an array so...

 

<?php
$qry = "SELECT * FROM `urtable`"; // swap this for your query string.
$qry = mysql_query($qry);

if (mysql_num_rows($qry) > 0)
{
$dataarr = array();
while($row = mysql_fetch_assoc($qry))
{
 foreach($row as $key => $val)
 {
  $dataarr[$key][] = $val;
 }
}
}
?>

 

OK so we no have an array of all the results (hope its not MASSIVE!!!!)

 

now all we need to do is see if the current weeknumber is in the corresponding array...

 

<?php
// $number_weeks = weeks in chosen year

for($i = 1;$i <= $number_weeks;$i++)
{
if (array_keys($dataarr['week'],$i))
 {
   echo "Exsisting in database!";
 }
}
?>

This solution is for making those weeks (who are containing text and such) I am printing in a table becoming marked. It's as easy as that.

So I wanted to identify who contained material and which who did not.

 

vbnullchar: Your solution was not working.

 

ToonMariner:

Interresting approach, can´t get it working though.

 

It returns:

Warning: array_keys() [function.array-keys]: The first argument should be an array

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.