mardi 1 mars 2016

Checking checkbox state and executing PHP query based on it

I have the following checkbox in a table:

<td><span id='checkbox'><input type='checkbox' name='secret' value='true'> Share Anomolously? </span></td>

I have altered my PHP code based on this previous question. I have the following code which executes two different queries based on whether the checkbox is checked or not:

$post_msg = @$_POST['msg'];

if (isset($_POST['secret'])=='true' && $post_msg != "" ) {
    // Checkbox is selected
    $posted_info = date('l jS \of F Y h:i:s A');
    //$date_of_msg  = date("Y-m-d");
    //$time_of_msg = date("H:i");
    $msg_sent_by  = $username;
    $insert_query = "INSERT INTO user_thoughts VALUES ('','$post_msg','','' ,'$attach_name','$msg_sent_by','')";
    $run_query = mysqli_query($connect, $insert_query) or die(mysqli_error());
} else if (isset($_POST['secret'])!=='true' && $post_msg != "" ) {
   // Alternate code
    $posted_info = date('l jS \of F Y h:i:s A');
    //$date_of_msg  = date("Y-m-d");
    //$time_of_msg = date("H:i");
    $msg_sent_by  = $username;
    $insert_query2 = "INSERT INTO user_thoughts VALUES ('','$post_msg','','' ,'$attach_name','$msg_sent_by','no')";
    $run_query2 = mysqli_query($connect, $insert_query2) ;
}

With this current piece of code, when a user hits the button to post their message $post_msg and the checkbox is not checked, it inserts no in the database, when it shouldn't. Just to explain, the last '' in the insert query INSERTS data to a column called shared, and has a defined value of yes.

So if the user posts a message, with the checkbox unchecked, it should execute the first if statement. And if the user shares a post with the checkbox checked, it should execute the second if statement which INSERTS no in column shared.

At the moment, it will always INSERT no in the shared column, even when the checkbox isn't checked.




Aucun commentaire:

Enregistrer un commentaire