php - Do not update with empty vars on UPDATE statement -
i trying run sql update dont want update when post vars empty.
code run :
require '../includes/db.php'; $settings_owner = ( isset($_post[wb_owner_field]) ? $_post[wb_owner_field] : false ); $settings_title = ( isset($_post[wb_title_field]) ? $_post[wb_title_field] : false ); $settings_description = ( isset($_post[wb_descr_field]) ? $_post[wb_descr_field] : false ); $settings_keywords = ( isset($_post[wb_keywd_field]) ? $_post[wb_keywd_field] : false ); $settings_id = ( isset($_post[wb_id]) ? $_post[wb_id] : false ); try { $sql = "update website set website_owner = '$settings_owner', website_title = '$settings_title', website_description = '$settings_description', website_keywords = '$settings_keywords' _id = '$settings_id' "; // prepare statement $stmt = $conn->prepare($sql); // execute query $stmt->execute(); // echo message update succeeded echo $stmt->rowcount() . " records updated successfully"; } catch (pdoexception $e) { echo $sql . "<br>" . $e->getmessage(); } $conn = null;
one way test value in update
statement:
$sql = "update website set website_owner = if('$settings_owner' = '', website_owner, '$settings_owner'), website_title = if('$settings_title' = '', website_title, '$settings_title'), website_description = if('$settings_description' = '', website_description, '$settings_description'), website_keywords = if('$settings_keywords' = '', website_keywords, '$settings_keywords') _id = '$settings_id' ";
another way build update
statement dynamically.
$sets = array(); if ($settings_owner != '') { $sets[] = "website_owner = '$settings_owner'"; } if ($settings_title != '') { $sets[] = "website_title = '$settings_title'"; } ... if (!empty($sets)) { $sql = "update website set " . implode(', ', $sets) . " _id = '$settings_id'"; $stmt = $conn->prepare($sql); $stmt->execute(); }
Comments
Post a Comment