Display 3 items per row - while loop - php/mysql

无人久伴 提交于 2019-12-12 10:25:34

问题


I am currently working on a loop to display items from a mysql table. Is there a simple way to display 3 items per row. So far I managed to display all the items in a single row inside an html table . I would appreciate any help; code (without html table tags) below:

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<?php
$database_name = "vog";
$conn = mysql_connect("localhost","root","toor");
mysql_select_db($database_name);

$sql = "select * from client1";

$result = mysql_query($sql) or die(mysql_error());
$num = mysql_num_rows($result); //Ελεγχος αν υπάρχουν εγγραφές!
?>

<?php
    if($num){
       while ($row = mysql_fetch_array($result))
    {
           echo $img_id = $row['img_id'];
 ?>

<form name="add2cart" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        <?php echo $row['img_name'];?>
        <?php echo "<img src=".$row['img_path'].">";?>
<select name="color">
    <option>bnw</option>
    <option>sepia</option>
</select>
<input type="hidden" name="img_name" value="<?php echo $row['img_name']; ?>"> 
<input type="submit" name="add2cart" value="Add to cart"></input>
        <br />
</form> 
<?php
        } 
    }
    else{
        echo "Δεν υπάρχουν εγγραφές με τα κριτήρια που επιλέξατε";
    }
    //add2cart section
if(isset($_POST['add2cart'])){   
$img_name = $_POST['img_name'];
$color = $_POST['color'];
$sql_order ="insert into orders(item_id, img_name, color) 
values(' ', '$img_name',    '$color')";
$result = mysql_query($sql_order);
}
?>

回答1:


Declare a variable before your loop like: $currentRow = 1 and then inside, and at the end, of your loop add $currentRow++

You can then check if your row is divisible by 3 if($currentRow % 3 == 0) and put a break in.



来源:https://stackoverflow.com/questions/8385165/display-3-items-per-row-while-loop-php-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!