关于php:PDO插入数组值

PDO insert array values

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

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

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

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

我需要将服务数组插入marketing_lookup表的帮助。
服务内容

我页面上的html表单

1
2
3
4
5
6
<form ....>
...
<input type='checkbox' name='services[]' value='1'>Service 1
<input type='checkbox' name='services[]' value='2'>Service 2
...
</form>

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
...
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值设置变量。 您应该检查其存在,然后仅将其设置为变量。

1
2
3
4
5
6
$id = $conn->lastInsertId(); // obtained from above (*)

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

其次,我假设您已经从(*)之前建立了连接-因此无需重新连接。 由于查询很短,因此可以使用?绑定参数,如示例3所示。

1
2
3
4
5
6
7
8
9
10
11
    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

您可能需要在进行多个插入操作时查看事务。


由于您已经创建了:id:serviceid的占位符,因此必须使用它而不是:1 or :2来绑定参数。

更改

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

1
2
$a = array  (':id'=>$serviceid['1'],
             ':serviceid'=>$serviceid['2']);