问题
I'm writing a small web service in PHP and I'm having a bit of trouble getting my head around the following scenario.
My plan is to be able to send an array of data to a function, which would then build a query for MySQL to run. In the array I plan for the key to be the column name, and the value to be the value going in to the columns.. i.e.
$myData = array('userName'=>'foo','passWord'=>'bar');
$myClass = new users();
$myClass->addUser($myData);
Then, in my function I currently have:
function addUser($usrData){
foreach($usrData as $col => $val){
// This is where I'm stuck..
}
}
Basically, I am wondering how I can separate the keys and values so that my query would become:
INSERT INTO `myTable` (`userName`,`passWord`) VALUES ('foo','bar');
I know I could probably do something like:
function addUser($usrData){
foreach($usrData as $col => $val){
$cols .= "," . $col;
$values .= ",'".$val."'";
}
}
But I thought there might be a more elegant solution.
This is probably something really simple, but I have never came across this before, so I would be grateful for any help and direction..
Thanks,
Dave
回答1:
Try this:
function addUser($usrData) {
$count = 0;
$fields = '';
foreach($usrData as $col => $val) {
if ($count++ != 0) $fields .= ', ';
$col = mysql_real_escape_string($col);
$val = mysql_real_escape_string($val);
$fields .= "`$col` = $val";
}
$query = "INSERT INTO `myTable` SET $fields;";
}
回答2:
EDIT:
Oops ! forgot quotation around VALUES( ), removing the old code
$query = "INSERT INTO `mytable` ( ".
mysql_real_escape_string(implode(array_keys(' , ', $userData))).
") VALUES ( '".
mysql_real_escape_string(implode("' , '", $userData)).
"' )";
回答3:
FYI, your code is wide open to SQL injection currently.
Use prepared queries with PDO. You can define your parameter names, and just pass an associative array to do the inserting.
You won't be able to stick an arbitrary array in there, as you will need to name your parameters appropriately (such as :userName
instead of userName
), but I don't think you want to do that anyway.
回答4:
My Bigginer (Easy) way to do it. It needs some refactoring, but it's quiet understandable for me.
public function insertArr( $table, $paramsArr) {
$sql = "INSERT INTO {$table} (";
foreach ( $paramsArr as $name=>$value ) {
$sql .="`$name`,";
}
$sql = substr($sql, 0, strlen($sql)-1);
$sql .= ") VALUES (";
foreach ($paramsArr as $name => $value){
$value === null? $sql .= "null," : $sql .= "'$value',";
}
$sql = substr($sql, 0, strlen($sql)-1);
$sql .= ");";
$this->link->query($sql);
return $this->link->affected_rows;
}
回答5:
Elegant solution:
function create_insert_query($tablename, $array) {
$key = array_keys($array);
$val = array_values($array);
//sanitation needed!
$query = "INSERT INTO $tablename (" . implode(', ', $key) . ") "
. "VALUES ('" . implode("', '", $val) . "')";
return($query);
}
回答6:
How about this one?
function addUser($usrData){
$query = "INSERT INTO `myTable` (`userName`, `passWord`) VALUES (:userName, :passWord);";
$stmt = $pdo->prepare($query);
foreach($usrData as $col => $val){
$stmt->bindValue(':'.$col, $val);
}
$stmt->execute();
}
It should do the job for you.
回答7:
Here is the code I tend to use for an insert query:
<?php
// Extend the PDO class, adding support for array to query binding
class db extends pdo{
// This makes the SQL insert query
function insert($keyValue){
if(is_array($keyValue)){
foreach($keyValue as $key => $value){
$fields[] = '`'.$key.'`';
$values[] = ':'.$key;
}
return '('.implode(' , ',$fields).') VALUES '.'('.implode(' , ',$values).')';
}
return '';
}
// Change the key to be :key to stop injections
function bind($keyValue){
if(is_array($keyValue)){
foreach($keyValue as $key => $value){
if(is_array($value)){ // if the value is array, lets assume I want an OR statement.
$count = -1;
foreach($value as $sValue){
$count++;
$where[':'.$key.$count] = $sValue;
}
} else {
$where[':'.$key] = $value;
}
}
return $where;
}
return array();
}
}
// It can be used like
try {
// Call the PDO class (Connect to the database).
$db= new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $pass);
} catch(PDOException $e) {
// If something goes wrong, PDO throws an exception with a nice error message.
echo $e->getMessage();
}
// The values you want to Add
$values = array('username' => $username, 'otherdata' => $otherdata);
$db->prepare('INSERT INTO `users` '.$db->insert($values).';') // The SQL statement.
->execute($db->bind($values)); // Bind the values to the query (Stopping SQL injections)
?>
回答8:
//This Will Help You To Insert Data Into Database by Array
$myData = array('user'=>'foo','name'=>'bar','player'=>'Sachin');
$get->adddd('tabelname',$myData);
function insert($tabel,$usrData) {
$count = 0;
$fields = '';
foreach($usrData as $col => $val) {
if ($count++ != 0) $fields .= ', ';
if($count==1){
$field .= $col;
$value .= "'".$val."'";
}
else{
$field .= ','.$col;
$value .= ",'".$val."'";
}
$fields .= "`$col` = $val";
}
mysql_query($query = "INSERT INTO $tabel ($field) VALUES ($value)");
}
来源:https://stackoverflow.com/questions/7051639/build-insert-query-from-array-mysql-and-php