我正在尝试使用 PHP 和 MySQL 自动更新我的"Products"
页面。我使用 MySQL 来存储我的产品 ID、产品名称、价格、数量等。我需要帮助让 PHP 获取 MySQL 数据并将每个 ID 放入<div>
一个特定的类中。
我想我需要一个while()
循环来获取数据数组和一个foreach()
循环来获取 ID 的每个实例,但我没有foreach()
正确使用循环。
请原谅我乱七八糟的编码。在我寻找更有效的做事方式之前,我试图将所有概念都记下来并发挥作用。请注意,其中sql2['id']
包含不止一项。
<?php
mysql_connect('localhost', 'user', 'password');
mysql_select_db('store');
$sql1 = mysql_query('
SELECT c.id,
c.name,
c.description,
c.price,
c.quantity,
c.itemid,
c.imgname,
c.position,
(SELECT Count(t.id)
FROM topics AS t
WHERE t.parent = c.id
AND t.id2 = 1) AS topics,
(SELECT Count(t2.id)
FROM topics AS t2
WHERE t2.parent = c.id
AND t2.id2 != 1) AS replies
FROM categories AS c
GROUP BY c.id
ORDER BY c.position ASC
');
if($sql1 === false){
die(mysql_error());
}
while($sql2 = mysql_fetch_array($sql1)){
foreach($sql2['id'] as $value){?>
<div class="itemInset">
<p><?php echo $sql2['name']; ?></p>
<img src="admin/image/<?php echo $sql2['imgName']; ?>" alt="<?php echo $sql2['imgName']; ?>" />
</div><?php
}
}
?>
SQL的分类:
CREATE TABLE IF NOT EXISTS `categories` (
`id` smallint(6) NOT NULL,
`name` varchar(256) NOT NULL,
`description` text NOT NULL,
`price` text NOT NULL,
`quantity` int(10) NOT NULL,
`itemID` text NOT NULL,
`cC` text NOT NULL,
`imgName` text NOT NULL,
`position` smallint(6) NOT NULL,
PRIMARY KEY (`id`),
KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
还有一个var_dump()
:
array(20) {
[0]=>
string(1) "1"
["id"]=>
string(1) "1"
[1]=>
string(9) "PC"
["name"]=>
string(9) "PC"
[2]=>
string(58) "computer "
["description"]=>
string(58) "computer "
[3]=>
string(6) "150.00"
["price"]=>
string(6) "150.00"
[4]=>
string(4) "1000"
["quantity"]=>
string(4) "1000"
[5]=>
string(8) "PCR-1000"
["itemID"]=>
string(8) "PCR-1000"
[6]=>
string(0) ""
["imgName"]=>
string(0) ""
[7]=>
string(1) "1"
["position"]=>
string(1) "1"
[8]=>
string(1) "0"
["topics"]=>
string(1) "0"
[9]=>
string(1) "0"
["replies"]=>
string(1) "0"
}