Jump to content

php,MySQL store checkbox values in database


kokotas

Recommended Posts

Hi,

 

I have this form which will create a checkbox list using data from my database and also determin if a checkbox had been checked before and check if it had.

 

<form style="text-align:center" name="PrefRestaurant" id="PrefRestaurant" action="preferances_check.php" method="post"><table align="center"> <?php checkbox(id, name, restaurants, id); ?></table>

<input type="submit" name="Prefer" id="Prefer" value="Επιλογή"/></form>

 

function checkbox($intIdField, $strNameField, $strTableName, $strOrderField, $strMethod="asc") {
$strQuery = "select $intIdField, $strNameField
               from $strTableName
               order by $strOrderField $strMethod";
    $rsrcResult = mysql_query($strQuery);


while ($arrayRow = mysql_fetch_assoc($rsrcResult)) {
	$testqry = "SELECT * FROM user_restaurant WHERE user_id = $_SESSION[userId] AND restaurant_id = $arrayRow[id]";
	$rsltestqry = mysql_query($testqry);
	$numrows = mysql_num_rows($rsltestqry);
	if ($numrows == 1) {
		echo "<tr align=\"left\"><td><input type=\"checkbox\" name=\"restaurant[]\" value=\"$arrayRow[id]\" checked/>$arrayRow[name]</td></tr>";
	}
	else{
	echo "<tr align=\"left\"><td><input type=\"checkbox\" name=\"restaurant[]\" value=\"$arrayRow[id]\" />$arrayRow[name]</td></tr>";
	}
}

}

 

 

Now the part which I can't get to work is when I'm trying to store the new values in my database. When I click the submit button I clear my database of any row that is related to the currently loggedin user and I want to store his new preferences (checked cheboxes). I've read that only the cheked checkboxes' values are POSTed so I did this (preferances_check.php)

 

foreach($_POST['restaurant']  as  $value)  {

$query="INSERT INTO user_restaurant VALUES ('$_SESSION[userId]','$value')";

}

 

 

But it is not working, nothing gets written in my table :( Could someone please enlighten me on this? Thnks!

Hi try this

 

$restaurant=$_POST['restaurant'];
foreach ($restaurant as  $value)  {
  $query="INSERT INTO user_restaurant (user_id, name) VALUES ('$_SESSION[userId]','$value')";
$res=mysql_query($query);
}

 

assuming user_id and name are the column names in your database

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.