【问题标题】:PDO insert array valuesPDO 插入数组值
【发布时间】: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) 看看你有什么键吗?

标签: php mysql arrays pdo


【解决方案1】:

由于您创建了 :id:serviceid 的占位符。您必须使用 this 而不是 :1 or :2 绑定参数

改变

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

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

【讨论】:

  • 喜欢这个@Saty? .... foreach ($services as $serviceid) { $a = array (':id'=>$id, ':service_id'=>$serviceid['1'], ':service_id'=>$serviceid[ '2'], .... 我遇到语法错误
  • 发布语法消息错误。并将其用作$a = array (':id'=&gt;$serviceid['1'], ':serviceid'=&gt;$serviceid['2']);
【解决方案2】:

首先,您的评估顺序错误。在检查 POST 值是否存在之前,您不应该使用 POST 值设置变量。您应该检查它的存在,然后仅当它存在时才将其设置为变量。

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

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

其次,我假设您之前 (*) 已经建立了连接——因此无需重新连接。由于您的查询很短,您可以使用? 绑定您的参数,如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

在进行多次插入时,您可能需要查看transactions

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 2020-12-11
    • 2012-08-25
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 2013-06-19
    相关资源
    最近更新 更多