PHP Form update MySql only if not null -
currently have update function update row if leave 1 of boxes empty, instead of not changing value value deleted. if need update 1 of values, update value , leave other boxes blank. possible?
currently code this.
<?php $key = $_post['key']; $value1 = $_post['value1']; $value2 = $_post['value2']; update table set value1 = '$value1',value2 = '$value2' key = '$key'; ?>
you have check each value see if it's blank, , if so, modify query string remove field set
clause.
something this:
<?php $set = array(); // create sure user doesn't effort post column doesn't exist in our table, // lead sql error, or worse, allow user run custom sql. $columns = array('value1', 'value2'); foreach ($_post $key=>$value) { if (in_array($key, $columns) && $value != '') { $set[] = $key ." = '". mysql_real_escape_string($value) ."'"; } } if (!empty($set)) { $query = "update table set ". implode(', ', $set) ." `key` = '". mysql_real_escape_string($_post['key']) ."'"; }
notice i've used mysql_real_escape_string()
. prevent sql injection. don't know mysql library you're using, should utilize appropriate sanitization method whatever you're using. , in actuality, shouldn't using regular mysql_*
library, it's deprecated. instead, recommend pdo.
php mysql
No comments:
Post a Comment