I'm trying to use PHP and MySQL to automatically update my "Products"
page. I use MySQL to store my product's IDs, Product name, price, quantity etc. I need help getting PHP to take the MySQL data and put each ID into a <div>
with a specific class.
I figured I needed a while()
loop to get the array of the data and a foreach()
loop to get each instance of the ID, but I am not using the foreach()
loop right.
Please excuse my mess of coding. I'm trying to get all the concepts down and working before I look for more efficient ways of doing things. Note that the sql2['id']
contains more than just one item.
<?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
}
}
?>
The categories 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;
And a 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"
}