【发布时间】:2016-09-29 02:40:57
【问题描述】:
我有一个表单,允许我将域插入到数据库中的“域”表中。
表单的一部分包括我为该域提供的服务列表,这些服务显示为一系列复选框并作为数组处理。这些服务被插入到一个 marketing_lookup 表中,该表有两列,分别是域 ID 和服务 ID。
我正在尝试使用 PDO 重写 mysql 插入语句。
我可以将域插入到域表中。
我需要帮助将服务数组插入到 marketing_lookup 表中。 服务
我页面上的html表单
<form ....>
...
<input type='checkbox' name='services[]' value='1'>Service 1<br>
<input type='checkbox' name='services[]' value='2'>Service 2<br>
...
</form>
到目前为止,我已经复制、粘贴和编辑了这个
...
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;
?>
【问题讨论】:
-
究竟是什么问题?你试过
var_dump($services)看看你有什么键吗?