onion2k
11-30-2004, 07:46 PM
$dbfield['first_name'] = "'".addslashes($_POST['firstname'])."'";
$dbfield['last_name'] = "'".addslashes($_POST['lastname'])."'";
$dbfield['email_address'] = "'".addslashes($_POST['email'])."'";
if ($_POST['id'] == 0) {
$sql = "insert into table (";
$sql .= implode(",",array_keys($dbfield));
$sql .= ") values (";
$sql .= implode(",",array_values($dbfield));
$sql .= ")";
} else {
foreach ($dbfield as $field => $value) {
$sqlarray[] = $field." = ".$value;
}
$sql = "update table set ";
$sql .= implode(", ",$sqlarray);
$sql .= " where id = '".$_POST['id']."'";
}
echo $sql;
Instead of building huge long strings of SQL just put everything into an associative array with the keys as the database column names, and the values as the form data.. and a little code at the end generates your SQL string. Magic.
I've been doing this sort of thing for agggggges, but the number of posts in other folders with great long SQL variables leads me to believe others might not have figured out the lazy way.. So I'm letting the cat out of the proverbial bag.
Aren't I nice?
EDIT: I know the code is a bit longer for 3 form fields than building a string.. just imagine you have 100 fields though..
$dbfield['last_name'] = "'".addslashes($_POST['lastname'])."'";
$dbfield['email_address'] = "'".addslashes($_POST['email'])."'";
if ($_POST['id'] == 0) {
$sql = "insert into table (";
$sql .= implode(",",array_keys($dbfield));
$sql .= ") values (";
$sql .= implode(",",array_values($dbfield));
$sql .= ")";
} else {
foreach ($dbfield as $field => $value) {
$sqlarray[] = $field." = ".$value;
}
$sql = "update table set ";
$sql .= implode(", ",$sqlarray);
$sql .= " where id = '".$_POST['id']."'";
}
echo $sql;
Instead of building huge long strings of SQL just put everything into an associative array with the keys as the database column names, and the values as the form data.. and a little code at the end generates your SQL string. Magic.
I've been doing this sort of thing for agggggges, but the number of posts in other folders with great long SQL variables leads me to believe others might not have figured out the lazy way.. So I'm letting the cat out of the proverbial bag.
Aren't I nice?
EDIT: I know the code is a bit longer for 3 form fields than building a string.. just imagine you have 100 fields though..