foreach, joined tables, stuff like that.
Date: 06/01/06
(PHP Community) Keywords: php
I'm currently trying to wrap my mind around multiple categories. So far the whole selecting works perfectly fine, but I can't figure out the how to post everything to the join table.
I don't understand how to use the cat_array and foreach elements. Can someone help me out? My PHP knowledge is still very basic and PHP.net just confuses me. Thank you :)
Relevant parts of the script (with some weird testing-stuff and some stuff commented out):
Currently, this version posts both an entry to the blog table, but it only posts one category into the catjoin table (always the one with the highest ID), however, it should of course make seperate entries for each checked category checkbox.
...
$cat_array = array();
....
<.form...>
...
# select the categories from the cat table to create a list of checkboxes
include('connect.php');
$result = mysql_query("SELECT blog_cat.catID, catname FROM blog_cat LEFT JOIN blog_catjoin ON blog_cat.catID=blog_catjoin.catID GROUP BY blog_cat.catID ORDER BY catname ASC") or print ("Can't select categories.
" . $result . "
" . mysql_error());
while($row = mysql_fetch_array($result)) {
$catID = $row["catID"];
$catname = $row["catname"];
echo "<.input type=\"checkbox\" name=\"$cat_array\" value=\"$catID\"";
echo " /> $catname ";
}
....
<./form>
....
# insert all the stuff into the database
$sql = "INSERT INTO $table (...) VALUES (....)";
$result = mysql_query($sql) or print ("Unable to post data.
" . $sql . "
" . mysql_error());
if ($result != false) {
print "Entry has been posted! ($title)";
}
$idresult = mysql_query("SELECT id from $table ORDER by id DESC LIMIT 1") or print ("Can't select categories.
" . $result . "
" . mysql_error());
while($idrow = mysql_fetch_array($idresult)) {
$id = $idrow["id"];
}
/*foreach ($cat_array as $cat) {*/
$query_cat = "INSERT INTO blog_catjoin VALUES ('','$id','$catID')";
$result_cat = mysql_query($query_cat);
if ($result_cat != false) {
echo "All categories successfully added.";
}
/*}*/
}
Source: http://community.livejournal.com/php/455794.html