我有一个从 $_POST 函数接收数组的函数,然后使用索引中包含的索引和值来创建 SQL。我的问题是我可以让函数正确回显 SQL,但我无法创建变量。我的功能如下
function createcontactsArray($sql,Array $contactsArray){
//array has already been cleaned from sql injections
//delete null variables and the value of the submit button
foreach ($contactsArray as $key => $value) {
if($value == ""||$value=="continue") {
unset($contactsArray[$key]);
}
}
echo "INSERT INTO users(";
//create list of tables to use in the database
foreach ($contactsArray as $key => $value) {
if ($value == end($contactsArray)) {
echo $key;
} else {
echo $key.",";
}
}
echo ') VALUES (';
//create list of tables to use in the database
//$newcontactsArray = array_values($contactsArray);
foreach ($contactsArray as $key => $value) {
if ($value == end($contactsArray)) {
echo '"'.$value.'"';
} else {
echo '"'.$value.'"'.",";
}
}
echo ');';
}
例如,如果您运行此脚本并将关联数组传递给$contacts = array("name"=>"Peter griffin","town"=>"Quahogn");
它,它将输出以下INSERT INTO users (name,contacts) VALUES ("Peter griffin","Quahog")
. 但是我希望该函数创建一个类似的 sql$sql = INSERT INTO users (name,contacts) VALUES ("Peter griffin","Quahog")
以便输出我只是说echo $sql;
谢谢。