我正在尝试使用Pear MDB2
对象来对我的数据库执行查询,但它不起作用。相反,我在Unable to bind to missing placeholder
上收到错误execute()
。我有一个sql builder函数,它将一个sql语句和参数返回给一个store数据函数,该函数也接受一个值数组来绑定到该语句。
注意:我将$params
替换为$_POST
,它们都是表单输入数组。除非我验证所有输入将其存储在对象中以供应用程序稍后使用,然后将其存储在数据库中。数据库连接是MDB2。
函数userinfo()
返回user
个对象变量。
public function build_sql_Insert($arry, $table)
{
if(!is_array($arry)){
return false;
}
$types = str_repeat("s", count($arry));
$keys = array_keys($arry);
$values = array_values($arry);
if ($table==="user") {
$sql = "INSERT INTO $table (" . implode(',', $keys) . ") VALUES (".implode(',', array_fill(0, count($values), '?')).")ON DUPLICATE KEY UPDATE ";
$updates = implode(',', array_map(function($col) {
return "$col = VALUES($col)";
}, $keys));
$sql .= $updates;
return $sql;
}
$sql = "INSERT INTO $table (" . implode(',', $keys) . ") VALUES (" .
implode(',', array_fill(0, count($values), '?')) . ")";
return $sql;
}
存储数据
public function storeData($sql, $cxn, $params){
if($stmt = $cxn->prepare($sql, MDB2_PREPARE_MANIP)){
$afft = $stmt->execute($params);
$stmt->free();
return 1;
}
return 0;
}
传递用户对象,该对象作为调用userInfo()
的数组返回:
WI_User Object
(
[UserId:WI_User:private] => 1
[FirstName:WI_User:private] => Natasha
[LastName:WI_User:private] => Harris
[Email:WI_User:private] => kevlwig@gmail.com
[Password:WI_User:private] => $2y$10$YrYZs24ihAcRYqBROemTUuTmUQCI4l0zO52pjPGIC2PfKn/tOHC1G
[UserPix:WI_User:private] =>
[Status:WI_User:private] => 1
)
SQL语句:
INSERT INTO user (UserId,FirstName,LastName,Email,Password,UserPix,Status) VALUES (?,?,?,?,?,?,?)ON DUPLICATE KEY UPDATE UserId = VALUES(UserId),FirstName = VALUES(FirstName),LastName = VALUES(LastName),Email = VALUES(Email),Password = VALUES(Password),UserPix = VALUES(UserPix),Status = VALUES(Status)
函数调用:
$userdata = $this->user->userInfo();
$sql = $this->build_sql_Insert($userdata, $this->moduleName);
$this->storeData($sql, $this->db, $userdata)