PDO插入阵列值 [英] PDO insert array values

查看:49
本文介绍了PDO插入阵列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,可以将域插入数据库中的"domains"表中.

I have a form which allows me to insert a domain to a 'domains' table in my database.

表单的一部分包括我为该域提供的服务列表,这些服务以一系列复选框的形式呈现,并以数组的形式进行处理.这些服务被插入到marketing_lookup表中,该表具有两列,分别具有域ID和服务ID.

Part of the form includes a list of services that I provide for that domain which are presented as a series of checkboxes and handled as an array. These services are inserted into a marketing_lookup table that has two columns the has the domain id and the service id.

我正在尝试使用PDO重写mysql插入语句.

I'm trying to rewrite mysql insert statements using PDO.

我可以编码将域插入域表.

I can code inserting the domain to the domains table.

我需要帮助将服务数组插入marketing_lookup表中. 服务

I need help inserting the services array into the marketing_lookup table. The services

我页面上的html表单

The html form on my page

<form ....>
...
<input type='checkbox' name='services[]' value='1'>Service 1<br>
<input type='checkbox' name='services[]' value='2'>Service 2<br>
...
</form>

到目前为止,我已经复制,粘贴和编辑了

I have copied and pasted and edited this so far

... 
code inserting the domain into the domain table here
...
//start inserting services here
if ($services == '') $services = array();
$services = $_POST['services']; 
$id = $conn->lastInsertId(); //obtained from above

if (!isset($_POST['services'])):
echo  'Nothing Selected';

else:
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 $stmt = $conn->prepare('INSERT IGNORE INTO marketing_lookup SET   
`domain_id` = :id,
`service_id` = :serviceid')

foreach ($services as $serviceid) {
$a = array  (':1'=>$serviceid['1'],
             ':2'=>$serviceid['2']);

 if ($stmt->execute($a)) {          
       //Query succeeded
            }
    else {
                // Query failed.
                echo $q->errorCode();
                }    
// close the database connection
$conn = null;   
} // end foreach
  } //end try

catch(PDOException $e) {
        echo $e->getMessage();
        }
endif;  
?>

推荐答案

首先,您的评估顺序不正确.在检查POST值是否存在之前,您不应该使用POST值设置变量.您应该检查它的存在,然后仅将其设置为变量.

First, your order of evaluation is wrong. You shouldn't be setting a variable with a POST value BEFORE checking if the POST value even exist. You should check its existence then set it into a variable only if it exist.

$id = $conn->lastInsertId(); // obtained from above (*)

if (!isset($_POST['services'])) {
    echo  'Nothing Selected';
} else {
    $services = $_POST['services']; // array(0 => 1, 1 => 2, ...)

第二,我假设您已经有了以前(*)的连接-因此无需重新连接.由于查询很短,因此可以使用?绑定参数,如示例#中所示3 .

Second, I'm assuming you already have a connection from before (*) -- so there's no need to reconnect. As your query is short, you can use ? to bind your parameters as shown in Example #3.

    try {
        $stmt = $conn->prepare('INSERT IGNORE INTO marketing_lookup SET domain_id = ?, service_id = ?');
        foreach ($services as $serviceId) {
            $stmt->execute(array($id, $serviceId));
        }
    } catch (PDOException $e) {
        echo $e->getMessage();
    }
}

$conn = null; // pointless

在进行多次插入操作时,您可能需要研究交易.

You might want to look into transactions as you are doing multiple inserts.

这篇关于PDO插入阵列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆