如何在php中的pdo prepare方法中编写公共插入查询

时间:2018-10-23 07:26:20

标签: php pdo

我正在尝试在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;
}
?>

我的operontons.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格式不正确。如何纠正这个问题。

1 个答案:

答案 0 :(得分:1)

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