views:

49

answers:

2

I am creating a very small database abstract layer, i want to send an array of variables that i obtained from a form, and generate an update sql statement, and eventually execute it. What do I put on the second to last line below? for example.

$table name = "user";
$username = $_post['username'];
$password = $_post['password'];
$email    = $_post['email'];
$array = (username=>$username, password=>$password, email=>$email);
$query = "update $this->tableName".
$query = """" The value from the assc array in the form of database vlaue='form value' 
$query = "WHERE condition";

i hope i made it clear enough. Thank you in advance

+2  A: 

You can use a foreach() loop to generate your query clause from your array. Note that you need to declare your array with the array() construct, and quote your associative keys.

//...
$array = array('username'=>$username, 'password'=>$password, 'email'=>$email);
$query = "update ".$this->tableName." SET ";
foreach($array as $field => $value) {
    $query .= "`".$field."`='".mysql_real_escape_string($value)."',";
}
//knock off trailing comma
$query = substr($query,0,-1);
$query .= " WHERE condition";
zombat
Thanks alot it works
zf
I am thinking of sending it as a multidimensional array for example $multi = array(); $multi[] = array($customer_id, $domain_name, $purchase_date, $expiry_date, $vendor); $multi[] = array("c_id", "domain_id", "purchase_date", "expiry_date", "vendor");how can you implement the foreach on this kind of array?
zf
A: 

You can use something like:

$a = array();
foreach($array as $key => $value)
{
    $a[] = $key . " = '" . mysql_real_escape_string($value) ."'";
}
$query = join(',', $a);

but you need to take care of special cases, for example when the value is null or a date

pedro