开发者

When exactly are PHP-MySQL variable assignments made?

[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 m开发者_如何学Pythonade 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 () ) ;
          }
    }


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());
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜