How to check if check box is clicked and send info to mySQL?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ilya Kraft
    New Member
    • Jan 2011
    • 134

    How to check if check box is clicked and send info to mySQL?

    Hi,

    I just started using check boxes to send information to mySQL. What I want to do is to send id of the user and article to database when check box is clicked and when it is un-clicked remove that information from database.

    Right now I am at this stage

    Code:
    <?php
    
    if (isset(//if user is logged in)) { 
    $addFavorite = '<input type="checkbox" id="favoriteIt" name="favoriteIt" />'; }
    else {
    $addFavorite = ""; }
    
    
    $asrticleDisplaylist = '<div>'.$addFavorite.'</div>';
    ?>
    So right now I display the check box for logged in user
    on every article that is on the page.
    What I want to do next is to somehow collect information from that check box, I assume that I will need to place check box inside <form method="post"> , but is it necessarily or can I somehow set method to post in the <input>?

    After that I will need to find out if check box is checked or not. So I can than update information. I don't think I understand code behind this part, but I know what I need could be explained like this (I will write //comments in parts that I don't understand) :

    Code:
    if //check box is clicked
    
    $sql =  mysql_query("INSERT INTO favorites (article_id, user_id) VALUES ($article_id, $user_id)");
    
    else
    
    if //check box is not checked
    
    //Delete stuff from database
    I don't know if it matters, but just in case I am using several check boxes on one page.

    Thank You
  • dlite922
    Recognized Expert Top Contributor
    • Dec 2007
    • 1586

    #2
    You must have a <form>

    the value="" attribute in the checkbox will be sent via whatever your form method is (post or get)

    example: <input type="checkbox" name="foo" value="bar" />.

    You can get this value by $_REQUEST['foo'].

    If the checkbox wasn't check, then isset($_REQUEST['foo']) will return false.

    Before putting this value in a MySQL database, clean it using mysql_real_esca pe_string() function to prevent hacking.


    Good luck,


    Dan

    Comment

    • ilya Kraft
      New Member
      • Jan 2011
      • 134

      #3
      Soo

      Code:
      mysql_real_escape_string($_REQUEST['foo'])
      
      if isset($_REQUEST['foo']) {
      
      $sql = mysql_query("INSERT INTO Favorites (article_id, user_id) VALUES ($article_id, $user_id)");
      
      }
      Will this do the job?

      Thnx

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        You can get this value by $_REQUEST['foo'].
        bear in mind that GET data overwrite POST data. and changing the action value is nothing complicated.

        Comment

        Working...