Hi

I need to know, is there any option to use For loop instead of While and ForEach to retrieve the result.

While Loop
-----------

$query  = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
    echo "Name :{$row['name']} <br>" .
}

instead to this , i need For Loop not For Each.

For Loop [Something like this]
--------

$stylequery="SELECT DoorID, DoorType
			FROM do_style
			WHERE DiyOrderID = '$orderId'" ;
$styleresult= mysql_query($stylequery,$con)
$row = $styleresult;

for($sloop = 0; $sloop < 2; $sloop++)
{
echo("<tr>
		<td style='width: 49px; height: 24px; text-align: center' title='Wall Cabinets'>
		$sloop
		</td>
		<td style='width: 61px; height: 24px'>$row[$sloop]['DoorType']
		</td>
	</tr>
	"
	)
}

Bcoz, I need to loop number of times and echo the html statements to get aligned the page layout even data are not there.


Thanks in Advance

I don't quite understand why for() would be better than while() in this case.

Anyway, here's an example:

$results = mysql_num_rows($result);
for($sloop = 0; $sloop < $results; $sloop++)
{
    $row = mysql_fetch_array($result);
    // do more stuff
}

.. I just thought you maybe wanted to loop x times whether theres more or less results.
Then try

for($sloop = 0; $sloop < 2; $sloop++)
{
    $row = mysql_fetch_array($result);
    if($row === false)
    {
        $doortype = "Unknown";
    }else
    {
        $doortype = $row['DoorTyp'];
    }
   
    // echo stuff <td>$doortype</td>
}

Hope this helps you :) Let me know!

$stylequery="SELECT DoorID, DoorType
			FROM do_style
			WHERE DiyOrderID = '$orderId'" ;
$styleresult= mysql_query($stylequery,$con)


$max = mysql_num_rows($styleresult);

for($i=0;$i<$max;$i++)
{
$row = mysql_fetch_array($sql);
echo "<tr>
		<td style='width: 49px; height: 24px; text-align: center' title='Wall Cabinets'>
		".$i."
		</td>
		<td style='width: 61px; height: 24px'>".$row['DoorType']."
		</td>
	</tr>
	";
	
}
Member Avatar for rajarajan2017
if (mysql_num_rows($result) > 0) { 
for($i = 0; $i < mysql_num_rows($result); $i++) {
	$row = mysql_fetch_array($result);
	 echo "<tr>"; 
     echo "<td>".$row[0]."</td>"; 
     echo "<td>" . $row[1]."</td>"; 
     echo "<td>".$row[2]."</td>"; 
     echo "</tr>"; 
}
echo "</table>"; 
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.