首页 > 解决方案 > 如何在 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 的方式不正确。如何纠正这一点。

标签: phppdo

解决方案


假设您的$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);

推荐阅读