本文介绍了每行显示3个项目-While循环-PHP/MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在循环显示mysql表中的项目.有没有一种简单的方法来显示每行3个项目.到目前为止,我设法将所有项目显示在html表内的一行中.我将不胜感激任何帮助;下面的代码(无html表标签):

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);
}
?>

推荐答案

在循环之前声明一个变量,例如:$currentRow = 1,然后在循环的内部和结尾添加$currentRow++

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

然后您可以检查您的行是否可被3 if($currentRow % 3 == 0)整除并插入一个中断.

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

这篇关于每行显示3个项目-While循环-PHP/MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:44