php - 如何在 php 的 pdo prepare 方法中编写常见的插入查询
问题描述
我正在尝试在 pdo prepare 语句中编写用于插入查询的通用代码。
index.php 是:
<?php
include('include/header.php');
$table_name = 'office';
if(isset($_POST['submit']))
{
include('functions.php');
$data = array();
$data = escapemydata($_POST);
unset($data['action']);
unset($data['submit']);
unset($data['id']);
$userprofileobj->insert($table_name,$data);
}
?>
<form method="post" action="#">
<table align="left" width="100%">
<tr>
<td><strong>Name</strong></td>
<td><input type="text" name="title" required="required" /></td>
</tr>
<tr>
<td><strong>Designation</strong></td>
<td><input type="text" name="desig" required="required" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Insert" /></td>
</tr>
</table>
</form>
functions.php 是:
<?php
function escapemydata($data = array())
{
foreach($data as $key => $value)
{
$data[$key] = $value;
}
return $data;
}
?>
我的operatorons.php,其中插入函数是:
public function insert($table,$data){
if(!empty($data) && is_array($data)){
$columns = '';
$values = '';
$i = 0;
foreach($data as $key=>$val){
$pre = ($i > 0)?', ':'';
$columns .= $pre.$key;
$values .= ":".$val.", ";
$i++;
}
foreach($data as $key => $value){
$data2[$data[$key]] = $data[$value];
}
$values = rtrim($values,', ');
$stmt = "INSERT INTO ".$table." (".$columns.") VALUES (".$values.")";
$stmt = $this->con->prepare($stmt);
$stmt->execute($data2);
}else{
$this->con->close();
return false;
}
}
但是查询没有插入任何数据。我认为 $stmt->execute($data2); 没有运行。因为 $data2 的方式不正确。如何纠正这一点。
解决方案
假设您的$data
数组具有:
$data = array("title" => "mrx", "desig" => "MD" );
您希望您的sql
查询是:
$columns = "title, desig";
$values = ":title, :desig";
$data2 = array(":title" => "mrx", ":desig" => "MD");
$stmt = "INSERT INTO ".$table." (".$columns.") VALUES (".$values.")";
$stmt = $this->con->prepare($stmt);
$stmt->execute($data2);
为了创建您可以使用的那些:
$columns = '';
$values = '';
$data2 = array();
foreach($data as $key=>$val){
$columns .= $key . ", ";
$values .= ":" . $key . ", ";
$data2[":" . $key] = $val;
}
//Remove last ', '
$columns = substr($columns, 0, -2);
$values = substr($values , 0, -2);
推荐阅读
- oracle - 在从 oracle db 导出到 csv 期间防止数字舍入
- php - 如何在 localhost 上提交我的代理和名称
- javascript - 在后台运行持久的 Web Worker 而不会受到限制
- mysql - VB.net连接失败的数据库MySql
- css - Css flex 调整移动版和桌面版的对齐方式
- python - ImportError:导入_multiarray_umath时DLL加载失败:找不到指定的模块
- java - Bipredicate 的类型安全容器
- php - 格式化txt文件
- html - 表头中的标题不应在 laravel 的 foreach 循环中重复
- python - Gimp 无法从 OSX 中的 shell 脚本正确启动