views:

30

answers:

1

[Status: learner] Using checkboxes, the user selects rows from a displayed HTML table. I then want to insert the date and the unique row id ("select_id") of the selected ('ticked') rows into a different table. Maybe I'm off-base, but it seems to me that the first block of code does not work. The second block of code does work. If I'm correct, it appears that it matters where the $SQL statement is made. WHY? I mean, no variable assignments are made until the $sql is called by the mysql_query() function, right?

(...If I'm wrong, nevermind, it is just a normal evening at home.)

$sql = "INSERT INTO sap_id_select (  select_date
                                   , select_id )
        VALUES (  CURRENT_DATE ()
                , '{$cSelected_id}' ) 
       " ;

if ( isset ( $_POST [ checkbox] ) ) 
   { 
      foreach ( $_POST [ checkbox ] as $cSelected_id )
         {
            mysql_query ( $sql ) or ( "Error: " . mysql_error () ) ;
         }
   }

================================

 if ( isset ( $_POST [ checkbox] ) ) 
    { 
       foreach ( $_POST [ checkbox ] as $cSelected_id )
          {
             $sql = "INSERT INTO sap_id_select (  select_date
                                                , select_id )
                     VALUES (  CURRENT_DATE ()
                             , '{$cSelected_id}' ) 
                    " ;

             mysql_query ( $sql ) or ( "Error: " . mysql_error () ) ;
          }
    }
A: 

In example one, the query is assuming the existence of a variable, which isn't there. If you want, you could parameterize the query, and add the values within the foreach, but you cannot do it as you're attempting in example 1.

Example:

$sql = "INSERT INTO sap_id_select(select_id) VALUES('%s')";

if (isset($_POST["checkbox"])) {
  foreach ($_POST["checkbox"] as $cSelected_id) {
    mysql_query ( sprintf($sql, $cSelected_id) ) or ("Error: ".mysql_error());
  }
}
Jonathan Sampson
Thank you, Johathan. If you will indulge me, why isn't the $sql statement a "bunch of text" prior to its usage by the mysql_query() function? [IOW, if I understand you correctly, the {$cSelected_id} assignment is made as soon as the $sql statement is parsed, and does NOT wait until it is put into action by mysql_query().]
dave
I believe that is the case, dave.
Jonathan Sampson
Well, dang! Just when I thought I'd learned something.
dave