查看数据库项目(foreach循环)需要做什么?
我已经创建了一个数据库。我想查看每个li标签内的每个mysql数据库item_name。可以用foreach循环完成吗?我需要为此做什么?谁能用下面的代码给我解决方案?
这是我现在拥有的代码:
*{margin:0; padding:0;}
.cont{
margin:200px 400px;
width:500px;
background:transparent;
color:black;
padding:20px;
box-shadow:1px 1px 4px 4px #ddd;
}
ul{
margin:0;
padding:0;
list-style:none;
}
ul li{
float:none;
}
.m-a-d{
display:inline-block;
color:black;
background:#ccc;
padding:5px 10px;
text-decoration:none;
opacity:0.4;
transition:0.3s;
}
ul li:hover .m-a-d{
text-decoration:underline;
opacity:1;
}
<?php
$conn = mysqli_connect("localhost", "root", "", "a1");
if(!$conn){
echo "Not Connected with localhost";
}
?>
<?php
require_once "init.php";
$sql = "SELECT * FROM items";
$query = $conn -> query($sql);
$rowcount = $query -> num_rows;
?>
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="style.css"/>
<body>
<div class="cont">
<h1>To do</h1>
<?php if(!empty($items)): ?>
<ul>
<?php foreach($items as $item): ?>
<li>
<span class="list"><?php $item['item_name']; ?></span>
<a href="#" class="m-a-d">Mark as done</a>
</li>
<?php endforeach;?>
</ul>
<?php else: ?>
<p>You haven't added any item yet.</p>
<?php endif; ?>
</div>
</body>
</html>
在此先感谢您的帮助。..............................
答案 0 :(得分:0)
这里是更新的php代码。
<?php
$conn = mysqli_connect("localhost", "root", "", "a1");
if(!$conn){
echo "Not Connected with localhost";
}
?>
<?php
require_once "init.php";
$sql = "SELECT * FROM users";
$resultSet = $conn -> query($sql); // here I replaced variable name to resultSet
$rowcount = $resultSet -> num_rows;
?>
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="style.css"/>
<body>
<div class="cont">
<h1>To do</h1>
<?php if($rowcount > 0): ?>
<ul>
<?php while($item = $resultSet->fetch_array()){ ?>
<li>
<span class="list"><?php $item['item_name']; ?></span>
<a href="#" class="m-a-d">Mark as done</a>
</li>
<?php }?>
</ul>
<?php else: ?>
<p>You haven't added any item yet.</p>
<?php endif; ?>
</div>
</body>
</html>
主要是,您尝试检查$items
的条件是否为foreach
,而没有结果集或名为$ items的变量。
所以我在第10行附近用$resultSet
更新,然后相应地更新了代码。