1

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 value='form value' 
$query = "WHERE condition";

2 Answers 2

3

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";
Sign up to request clarification or add additional context in comments.

1 Comment

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?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.