Jump to content

For Loops


Triple_Deuce

Recommended Posts

Ok, I have code that I have made and i need to format it's output into a sort of table...

 

$db_name = "tripled_vpa";
$connection = @mysql_connect("localhost", "tripled_user", "triple222") or die(mysql_error());
$db = @mysql_select_db($db_name, $connection) or die(mysql_error());

$count = 0;
$test = 0;
$breed = "Brittany";
$showid=5;
////////////////////////////////////////////////////

$showinfo = "SELECT * FROM shows WHERE showid='$showid'";
$infoshow = @mysql_query($showinfo,$connection) or die(mysql_error());
while ($row = mysql_fetch_array($infoshow)) 
{
$type = $row['type'];
$showname = $row['name'];
$shnum = $row['show_num'];
$close = $row['close'];
}

echo "Viewing Entires of: <b>$breed</b><Br><Br>";

$getentries = "SELECT * FROM entries WHERE breed = '$breed' AND show_num='$showid'";
$entryget = @mysql_query($getentries,$connection) or die(mysql_error());

while ($row = mysql_fetch_array($entryget)) 
{
++$count;
    $show_num= $row['show_num'];
$image= $row['image'];
$s_name= $row['s_name'];
$gender= $row['gender'];
$breed= $row['breed'];
$age= $row['age'];
$owner= $row['owner'];
$vpa_num= $row['vpa_num'];

if($age >= 1 && $age <= 59 )
{	$age = "Young";		}
else if($age >= 60 && $age <= 210 )
{	$age = "Adult";		}
else if($age >= 211 && $age <= 360 )
{	$age = "Senior";	}
else if($age > 360)
{	$age = "Retired";	}

	echo <img src=\"$image\"><BR>
        <b>$s_name</b><br>   
        VPA#$vpa_num<Br> 
		Gender: $gender<Br>
		Age: $age<Br>
		Owner: $owner";
}

 

I have gotten this:

 

echo "<table>";
for ( $i = 0; $i < $count; ++$i) 
{
echo "<tr>";
for ( $n = 0; $n < 4; ++$n) 
{
//this was taken from above just showing where i want it.
echo "<td align=\"center\"><img src=\"$image\"><BR>
        <b>$s_name</b><br>   
        VPA#$vpa_num<Br> 
		Gender: $gender<Br>
		Age: $age<Br>
		Owner: $owner</td>";
}
echo "</tr>";
}
echo "</table>";

 

but it doesnt print out the different ones, it prints out the same entry...  I need it to print a different entry in each

<td></td>

 

Help me, i am unsure how to get it to give the entries different 'names' or a way of calling the different ones...

 

hope that makes since... thanks

Link to comment
Share on other sites

You have:

 

$type = $row['type'];

$showname = $row['name'];

$shnum = $row['show_num'];

$close = $row['close'];

 

You're echoing:

 

<td align=\"center\"><img src=\"$image\"><BR>

<b>$s_name</b><br>   

VPA#$vpa_num<Br>

Gender: $gender<Br>

Age: $age<Br>

Owner: $owner</td>

 

So, none of the variables you pulled from the database are being used. Dunno what the deal is there...

 

PhREEEk

 

Link to comment
Share on other sites

No, if you go down in the code a lil further you will see the variables i am using

while ($row = mysql_fetch_array($entryget))

 

 

this is what i have in the original code:

 

echo <img src=\"$image\"><BR>
        <b>$s_name</b><br>   
        VPA#$vpa_num<Br> 
		Gender: $gender<Br>
		Age: $age<Br>
		Owner: $owner";

 

i left it in the original area just for comparison

Link to comment
Share on other sites

It seems that you are executing a while loop and assigning the values to static variables instead of arrays. That means that the data you end up echoing is going to be the last record that the while loop pulled.

 

So:

 

<?php
while ($row = mysql_fetch_array($entryget)) 
{
++$count;
    $show_num[]= $row['show_num'];
$image[]= $row['image'];
$s_name[]= $row['s_name'];
$gender[]= $row['gender'];
             // etc etc...
}

 

will properly populate those variables as arrays. But this seems like just poorly written code to begin with. If you could post a COMPLETE script, I can re-write you something that works.

 

PhREEEk

Link to comment
Share on other sites

Also here

 

while ($row = mysql_fetch_array($infoshow)) 
{
  $type = $row['type'];
  $showname = $row['name'];
  $shnum = $row['show_num'];
  $close = $row['close'];
}

 

Try this

while ($row = mysql_fetch_array($infoshow)) 
  $info[] = $row;

print_r($info);

 

For troubleshooting tips on arrays...use print_r function to check if it is populated properly

 

Link to comment
Share on other sites

Good Day,

 

Ahm, I'm not really an expert when it comes to PHP, but, I think, you have your "mysql_fetch_array" syntax is incorrect, it is missing one parameter to get an array of associative indices and it is "MYSQL_ASSOC".

 

So, instead of writing it like this:

->$row = mysql_fetch_array($infoshow)

 

you should write it like this:

->$row = mysql_fetch_array($infoshow,MYSQL_ASSOC)

 

Regards,

Link to comment
Share on other sites

<?php

//Connect to database
$db_name = "tripled_vpa";
$connection = @mysql_connect("localhost", "tripled_user", "triple222") or die(mysql_error());
$db = @mysql_select_db($db_name, $connection) or die(mysql_error());

$count = 0;
$test = 0;
$breed = "Brittany";//test
$showid=5;//test
////////////////////////////////////////////////////

$showinfo = "SELECT * FROM shows WHERE showid='$showid'";
$infoshow = @mysql_query($showinfo,$connection) or die(mysql_error());
while ($row = mysql_fetch_array($infoshow)) 
{
$type = $row['type'];
$showname = $row['name'];
$shnum = $row['show_num'];
$close = $row['close'];
}

echo "Viewing Entires of: <b>$breed</b><Br><Br>";

echo "<table>";

$getentries = "SELECT * FROM entries WHERE breed = '$breed' AND show_num='$showid'";
$entryget = @mysql_query($getentries,$connection) or die(mysql_error());

while ($row = mysql_fetch_array($entryget)) 
{
++$count;
    $show_num= $row['show_num'];
$image= $row['image'];
$s_name= $row['s_name'];
$gender= $row['gender'];
$breed= $row['breed'];
$age= $row['age'];
$owner= $row['owner'];
$vpa_num= $row['vpa_num'];

if($age >= 1 && $age <= 59 )
{	$age = "Young";		}
else if($age >= 60 && $age <= 210 )
{	$age = "Adult";		}
else if($age >= 211 && $age <= 360 )
{	$age = "Senior";	}
else if($age > 360)
{	$age = "Retired";	}

echo "<tr><td align=\"center\">
	<img src=\"$image\"><BR>
	<b>$s_name</b><br>   
	VPA#$vpa_num<Br> 
	Gender: $gender<Br>
	Age: $age<Br>
	Owner: $owner</td></tr>";
}

echo "</table><Br>";

////////////////////////////////////////////////////

//I know that I have the stuff in two different places, 
//the above works but puts it straight down the page, 
//i left it in to be able to see correct information

////////////////////////////////////////////////////

echo "<table>";
for ( $i = 0; $i < $count; ++$i) 
{
echo "<tr>";
for ( $n = 0; $n < 4; ++$n) 
{

echo "<td align=\"center\"><img src=\"$image\"><BR>
        <b>$s_name</b><br>   
        VPA#$vpa_num<Br> 
		Gender: $gender<Br>
		Age: $age<Br>
		Owner: $owner</td>";
}
echo "</tr>";
}
echo "</table>";
?>

Link to comment
Share on other sites

Good Day,

 

Ahm, I'm not really an expert when it comes to PHP, but, I think, you have your "mysql_fetch_array" syntax is incorrect, it is missing one parameter to get an array of associative indices and it is "MYSQL_ASSOC".

 

So, instead of writing it like this:

->$row = mysql_fetch_array($infoshow)

 

you should write it like this:

->$row = mysql_fetch_array($infoshow,MYSQL_ASSOC)

 

Regards,

 

MYSQL_ASSOC is a constant passed on an optional parameter that gives you associative induces.

 

Back to the question...What exactly are you trying to do?

Nevertheless try this...if this is the data you have in mind.

 

$query = "SELECT s.type,s.name,s.showid,s.close,b.image,b.s_name,b.gender,b.breed,b.age,b.owner,b.vpa_num FROM shows s JOIN breed b ON b.show_num=s.showid WHERE s.showid='$showid' AND b.breed='$breed'";
$result=mysql_query($query,MYSQL_ASSOC));
while($row=mysql_fetch_array($result,MYSQL_ASSOC))
  $data[]=$row;
mysql_free_result($result);
print_r($data);

Link to comment
Share on other sites

Here is your script, slightly re-formatted:

 

<?php

//Connect to database
$db_name = "tripled_vpa";
$connection = @mysql_connect("localhost", "tripled_user", "triple222") or die(mysql_error());
$db = @mysql_select_db($db_name, $connection) or die(mysql_error());

$count = 0;
$test = 0;
$breed = "Brittany";//test
$showid=5;//test
////////////////////////////////////////////////////

$showinfo = "SELECT * FROM `shows`
             WHERE `showid` = '$showid'
            ";
$infoshow = mysql_query($showinfo,$connection) or die(mysql_error());
while ($row = mysql_fetch_array($infoshow)) 
{
    $type = $row['type'];
    $showname = $row['name'];
    $shnum = $row['show_num'];
    $close = $row['close'];
}
$getentries = "SELECT * FROM `entries`
               WHERE `breed` = '$breed'
               AND `show_num` =`'$showid'
              ";
$entryget = mysql_query($getentries,$connection) or die(mysql_error());

echo "<p>
Viewing Entires of: <b>$breed</b></p>
";
echo "<p>
<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">
";
while ($row = mysql_fetch_array($entryget)) {
    ++$count;
    $show_num= $row['show_num'];
    $image= $row['image'];
    $s_name= $row['s_name'];
    $gender= $row['gender'];
    $breed= $row['breed'];
    $age= $row['age'];
    $owner= $row['owner'];
    $vpa_num= $row['vpa_num'];

    if( $age >= 1 && $age <= 59 ) {
        $age = "Young";
    }elseif( $age >= 60 && $age <= 210 ) {
        $age = "Adult";
    }elseif( $age >= 211 && $age <= 360 ) {
        $age = "Senior";
    }elseif( $age > 360 ) {
        $age = "Retired";
    }

    echo "  <tr>
    <td align=\"center\">
      <img src=\"$image\">
      <br>
      <b>$s_name</b>
      <br>   
      VPA#$vpa_num
      <Br> 
      Gender: $gender
      <br>
      Age: $age
      <br>
      Owner: $owner
    </td>
  </tr>
";
}

echo "</table>
<br>
";

////////////////////////////////////////////////////

//I know that I have the stuff in two different places, 
//the above works but puts it straight down the page, 
//i left it in to be able to see correct information

////////////////////////////////////////////////////

echo "<table>";
for ( $i = 0; $i < $count; ++$i) 
{
    echo "  <tr>";
    for ( $n = 0; $n < 4; ++$n) {
        echo "    <td align=\"center\">
      <img src=\"$image\">
      <br>
      <b>$s_name</b>
      <br>   
      VPA#$vpa_num
      <br> 
      Gender: $gender
      <br>
      Age: $age
      <br>
      Owner: $owner
    </td>
";
    }
    echo "</tr>";
}
echo "</table>";
?>

 

Ok, your question is, "the first WHILE loop works (displays unique records), while the second FOR loop displays the same record, $count number of times. Why is this?"

 

Let's define some 'dots', then you can connect the dots for the understanding of the answer.

 

<?php
$count = 0;
$a = 'dog';
$count++;
echo $a . "<br>"; // prints dog to the screen, $count = 1
$a = 'cat';
$count++;
echo $a . "<br>"; // prints cat to the screen, $count = 2
for ($i = 0; $i < $count; $i++) {
    echo $a . "<br>"; // will print cat to the screen 2 times. dog will never print
}
?>

 

$a WAS dog, but was overwritten by cat. $a will never be dog again, unless we redefine it as dog. $a will ALWAYS be cat unless we redefine it as something else. $a will always be the LAST THING we told it it is. Arrays work differently, allowing us to retain multiple values for $a.

 

<?php
$count = 0;
$a[] = 'dog';
echo $a[$count] . "<br>"; // prints dog to the screen, $count = 1
$count++;
$a[] = 'cat';
echo $a[$count] . "<br>"; // prints cat to the screen, $count = 2
$count++;
for ($i = 0; $i < $count; $i++) {
    echo $a[$i] . "<br>"; // will print dog then cat to the screen.
}
?>

 

Ok? So in example 1, $a held one value at a time. In example 2, $a could have more than one value, and those values are held.

 

While $a as an array can have multiple values, it also can be overwritten with new values, just like it could be as a single value variable. So:

 

<?php
$count = 0;
$a[] = 'dog';
echo $a[$count] . "<br>"; // prints dog to the screen, $count = 1
$count++;
$a[] = 'cat';
echo $a[$count] . "<br>"; // prints cat to the screen, $count = 2
$count++;
for ($i = 0; $i < $count; $i++) {
    echo $a[$i] . "<br>"; // will print dog then cat to the screen.
}
$count = 0;
$a[$count] = 'cow';
echo $a[$count] . "<br>"; // prints cow to the screen, $count = 1
$count++;
$a[$count] = 'horse';
echo $a[$count] . "<br>"; // prints horse to the screen, $count = 2
$count++;
for ($i = 0; $i < $count; $i++) {
    echo $a[$i] . "<br>"; // will print cow then horse to the screen.
}
?>

 

So, at one time, $a[0] was dog, and $a[1] was cat. Then we changed that to $a[0] equals cow, and $a[1] equals horse. Dog and cat are GONE from the $a array.

 

Now, let's move on to the MySQL query. When you define a query (which means 'request'), you are asking MySQL to retreive ALL of the records that match your filters (which could be 0, or any positive number of records). When you submit the query, MySQL does NOT deliver all of the records right then. It creates a resource which points to those records. Let's examine your query, and the resulting resource:

 

<?php
$getentries = "SELECT * FROM `entries`
               WHERE `breed` = '$breed'
               AND `show_num` =`'$showid'
              ";
$entryget = mysql_query($getentries,$connection) or die(mysql_error());
?>

 

$getentries is your query, and the resource is assigned to $entryget. Therefore, $entryget is not a normal variable that you are used to working with. It is a POINTER, and it is pointing to the FIRST record that MySQL says it found. Using a WHILE loop, we can ask PHP that, WHILE the resource $entryget is pointing at a record, assign the current record to an array ($row), then perform the code (if any) between our WHILE braces. Usually this is assigning single variables to the array values (this isn't necessary really, just saves typing down the road), and then formatting the record into something that will go out to the screen, or a function, or whatever. So:

 

<?php
while ($row = mysql_fetch_array($entryget)) {
    //do this stuff
}
?>

 

So, $row will be our array (refer to the array example above.. we are starting to connect the dots!). WHILE $entryget is pointing to Record #1, $row[] is populated with the values for the fields in that record (since you asked for '*', ALL fields will be returned). So, for the first loop iteration, $row[] equals Record #1. You perform some code between the braces. When the loop runs out of code, it asks $entryget if there are any more records. $entryget says 'TRUE' (there ARE more records), so $row[] is assigned the values of Record #2.

 

Let's connect a dot here. Refer to the above, where 'dog' was overwritten by 'cat', and so 'dog' did not exist any longer. Same thing here. $row[] with Record #1's values is NOW GONE, replaced with Record #2's values. The nerve! = )

 

Ok, so eventually WHILE will ask $entryget if there are more records, and $entryget will announce 'FALSE' (no more records exist). WHILE will exit and PHP will continue with the code below the WHILE loop. What became of $row? It retains the LAST VALUE it received, which was the last record MySQL provided. Again, connect the dots. This is the same concept as changing the values for the $a array above. The old values are LOST, and the current value is the LAST value assigned.

 

Ok, back to your code. Inside your WHILE loop, you assign single value variables to $row's array key values. Those single value variables are treated exactly as $a above, and every time you assign them a new value to echo out to your table, the previous value is lost. The last value they were assigned is what they will KEEP.

 

So, what can we say about the state of our variables once the WHILE loop is finished? We can say:

 

$row[] is an array and contains the values for the LAST record $entryget pointed us to.

$s_name contains the value from $row['s_name'] for the LAST record $entryget pointed us to.

and so all the rest of your variables meet the same fate, and all are assigned the LAST record value.

 

Then you ask PHP:

 

<?php
echo "<table>";
for ( $i = 0; $i < $count; ++$i) 
{
    echo "  <tr>";
    for ( $n = 0; $n < 4; ++$n) {
        echo "    <td align=\"center\">
      <img src=\"$image\">
      <br>
      <b>$s_name</b>
      <br>   
      VPA#$vpa_num
      <br> 
      Gender: $gender
      <br>
      Age: $age
      <br>
      Owner: $owner
    </td>
";
    }
    echo "</tr>";
}
echo "</table>";
?>

 

Knowing what you know now, is there any question why you are getting the same record in the table rows, $count number of times? Is there any surprise that it's the LAST record MySQL sent us?

 

Now, I have no idea why you'd want the SAME information displayed the SAME WAY twice. Perhaps you are just testing your output, who knows. Just for fun, here's a neat way to 'save' output for use any number of times (we call this a "poor man's cache").

 

<?php
//Connect to database
$db_name = "tripled_vpa";
$connection = @mysql_connect("localhost", "tripled_user", "triple222") or die(mysql_error());
$db = @mysql_select_db($db_name, $connection) or die(mysql_error());

$count = 0;
$test = 0;
$breed = "Brittany";//test
$showid=5;//test
////////////////////////////////////////////////////

$getentries = "SELECT * FROM `entries`
               WHERE `breed` = '$breed'
               AND `show_num` =`'$showid'
              ";
$entryget = mysql_query($getentries,$connection) or die(mysql_error());

$content = "<p>
Viewing Entires of: <b>$breed</b></p>
";
$content .= "<p>
<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">
";
while ($row = mysql_fetch_array($entryget)) {
    // ++$count; We don't need this for anything
    $show_num= $row['show_num'];
    $image= $row['image'];
    $s_name= $row['s_name'];
    $gender= $row['gender'];
    $breed= $row['breed'];
    $age= $row['age'];
    $owner= $row['owner'];
    $vpa_num= $row['vpa_num'];

    if( $age >= 1 && $age <= 59 ) {
        $age = "Young";
    }elseif( $age >= 60 && $age <= 210 ) {
        $age = "Adult";
    }elseif( $age >= 211 && $age <= 360 ) {
        $age = "Senior";
    }elseif( $age > 360 ) {
        $age = "Retired";
    }

    $content .= "  <tr>
    <td align=\"center\">
      <img src=\"$image\">
      <br>
      <b>$s_name</b>
      <br>   
      VPA#$vpa_num
      <Br> 
      Gender: $gender
      <br>
      Age: $age
      <br>
      Owner: $owner
    </td>
  </tr>
";
}

$content .= "</table>
<br>
";

// echo $content;
?>

 

What we've done here, is instead of echoing to screen, we have echoed directly into a variable, $content. If you run this code, nothing will print to the screen. If you uncomment the echo statement at the bottom of the script, you will get your output. You can do more code, then echo $content again and there's your content again. You don't need to re-query MySQL and loop over every thing again unless you need a new record set based on different filtering criteria. If I were to re-write your script so that it prints out the same information twice, I'd have done this:

 

<?php
//Connect to database
$db_name = "tripled_vpa";
$connection = @mysql_connect("localhost", "tripled_user", "triple222") or die(mysql_error());
$db = @mysql_select_db($db_name, $connection) or die(mysql_error());

$count = 0;
$test = 0;
$breed = "Brittany";//test
$showid=5;//test
////////////////////////////////////////////////////

$getentries = "SELECT * FROM `entries`
               WHERE `breed` = '$breed'
               AND `show_num` =`'$showid'
              ";
$entryget = mysql_query($getentries,$connection) or die(mysql_error());

$content = "<p>
Viewing Entires of: <b>$breed</b></p>
";
$content .= "<p>
<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">
";
while ($row = mysql_fetch_array($entryget)) {
    // ++$count; We don't need this for anything
    $show_num= $row['show_num'];
    $image= $row['image'];
    $s_name= $row['s_name'];
    $gender= $row['gender'];
    $breed= $row['breed'];
    $age= $row['age'];
    $owner= $row['owner'];
    $vpa_num= $row['vpa_num'];

    if( $age >= 1 && $age <= 59 ) {
        $age = "Young";
    }elseif( $age >= 60 && $age <= 210 ) {
        $age = "Adult";
    }elseif( $age >= 211 && $age <= 360 ) {
        $age = "Senior";
    }elseif( $age > 360 ) {
        $age = "Retired";
    }

    $content .= "  <tr>
    <td align=\"center\">
      <img src=\"$image\">
      <br>
      <b>$s_name</b>
      <br>   
      VPA#$vpa_num
      <Br> 
      Gender: $gender
      <br>
      Age: $age
      <br>
      Owner: $owner
    </td>
  </tr>
";
}

$content .= "</table>
<br>
";

echo $content . "<br>". $content;
?>

 

PhREEEk

Link to comment
Share on other sites

Apologies then. I thought part of helping people was explaining why things behave the way they do. Then I thought if, by educating them, they might become better programmers, start asking less questions (because they can help themselves), and start answering questions intelligently for other newbies.

 

I could have been wrong.

 

PhREEEk

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.