I'm making a user preference page where the user can check off boxes and submit them to the DB so that when the page is reloaded the boxes they previously checked will be displayed as checked. The code "works" but doesn't work as expected as my array is submitting A instead of 0 or 1 into the DB. Please remember this is a mock-up of the final product and is not in the production environment.
The logic (from beginning of code to end) is this:
1: A DB connection is made (a column exists named preferences and is varchar256) and returned is the data in the array stored in column preferences.
2: Parse the data in the array to see if the checkboxes have a value of 0 or 1 and check the boxes as required. If no value for a checkbox is found in the DB then assign one with value of 0 which will be processed if the user clicks submit.
3: Now that the page has been loaded on the users screen, if the user were to check or uncheck a box the POST conditions kick in and submit the new checkbox state to the DB (either 0 or 1) and reloads the page.
The problem is $preference_submit() is submitting A into the DB not 0 or 1 which as you can see detonates my logic since my code is looking for 0's or 1's. Looking forward to reading your inputs on my first question here on stack.
My code:
<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{
header("Location: /login/");
}
$result=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userInfo=mysql_fetch_assoc($result);
$db_preferences = $userInfo['preferences'];
print_r($db_preferences['preference1']); //this returns A
print_r($db_preferences['preference2']); //this returns A
$preference_submit = array("preference1"=>$preference1, "preference2"=>$preference2);
?>
<form action="" method="post">
<tr> <td>1st Test Checkbox: </td><td><?php echo "<input type='checkbox' name='preference1' id='preference1' ";
if ($db_preferences['preference1']==1) {
echo "checked ";
}
else {
$preference_submit['preference1'] = "0";
}
echo "value='1'>";?>
<tr> <td>2nd Test Checkbox: </td><td><?php echo "<input type='checkbox' name='preference2' id='preference2' ";
if ($db_preferences['preference2']==1) {
echo "checked ";
}
else{
$preference_submit['preference2'] = "0";
}
echo "value='1'>";?>
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
print_r($preference_submit); /* returns this:
Array ( [preference1] => 0 [preference2] => 0 ) insert success
Even when I check off a box & click submit, the values stay 0 because of my else statement
since $db_preferences['preference1'] and $db_preferences['preference2'] both return A
*/
if(isset($preference_submit) && $preference_submit != ""){
$db_user = $userInfo['user_id'];
$s = "UPDATE users SET preferences='$preference_submit' WHERE user_id=$db_user";
$res=mysql_query($s);
if($res){
echo "insert success";
}else{
die(mysql_error());
}
}
}
?>
Aucun commentaire:
Enregistrer un commentaire