我正在用PHP编写一个小型Web服务,我在以下场景中遇到了一些麻烦。
我的计划是能够将一个数据数组发送到一个函数,然后该函数将构建一个MySQL运行查询。在数组中,我计划将键作为列名,并将值作为列中的值...即
$myData = array('userName'=>'foo','passWord'=>'bar');
$myClass = new users();
$myClass->addUser($myData);
然后,在我的功能中,我目前有:
function addUser($usrData){
foreach($usrData as $col => $val){
// This is where I'm stuck..
}
}
基本上,我想知道如何分离键和值,以便我的查询变为:
INSERT INTO `myTable` (`userName`,`passWord`) VALUES ('foo','bar');
我知道我可以做类似的事情:
function addUser($usrData){
foreach($usrData as $col => $val){
$cols .= "," . $col;
$values .= ",'".$val."'";
}
}
但我认为可能会有更优雅的解决方案。
这可能是非常简单的事情,但我以前从未遇到过这个问题,所以我会感激任何帮助和方向..
谢谢,
戴夫
答案 0 :(得分:8)
试试这个:
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;";
}
答案 1 :(得分:2)
编辑:
哎呀!忘了引用VALUES(),删除旧代码
$query = "INSERT INTO `mytable` ( ".
mysql_real_escape_string(implode(array_keys(' , ', $userData))).
") VALUES ( '".
mysql_real_escape_string(implode("' , '", $userData)).
"' )";
答案 2 :(得分:1)
仅供参考,您的代码目前对SQL注入非常开放。
使用prepared queries with PDO。您可以定义参数名称,只需传递一个关联数组即可进行插入。
你将无法在那里粘贴任意数组,因为你需要适当地命名参数(例如:userName
而不是userName
),但我不认为你无论如何都想这样做。
答案 3 :(得分:0)
这个怎么样?
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();
}
它应该为你做好准备。
答案 4 :(得分:0)
以下是我倾向于用于插入查询的代码:
<?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)
?>
答案 5 :(得分:0)
//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)");
}
答案 6 :(得分:0)
优雅的解决方案:
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);
}