【问题标题】:Check if value exists in array before inserting into database在插入数据库之前检查数组中是否存在值
【发布时间】:2014-05-20 10:25:21
【问题描述】:

我有一个从 API 返回的数组,尽管某些键/值并非一直都存在。

示例数组

Array
(
    [example0] => data
    [example1] => data
    [example2] => data
    [example3] => data
)

现在如果我使用如下查询

$dbh = $this->database->prepare("INSERT INTO table(example0, example1, example2, example3)VALUES(:example0, :example1, :example2, :example3)");
    $dbh->execute(array(
        "example0" => $data['example0'],
        "example1" => $data['example1'],
        "example2" => $data['example2'],
        "example3" => $data['example3']
    ));

它会正常工作的。但是当 API 返回一个类似

的数组时
Array
(
    [example0] => data
    [example1] => data
    [example3] => data
)

由于没有设置值会导致错误,有没有办法让它在列中不输入任何内容而不是抛出错误?我为此使用了一个非常大的查询,因此为每个值编写一个 if/else 不是一个好主意(在我看来,出于性能考虑)

【问题讨论】:

    标签: php arrays pdo


    【解决方案1】:

    您必须检查是否设置了键,最终是否有值:

    if(isset($array['your_key']) && !empty($array['your_key'])) { } 
    

    我无法从您的代码中说清楚,但在您在查询中使用它之前验证所有内容。

    [编辑]示例:

    $keys = array('example1', 'example2', 'example3', 'example4');
    $use_in_query = array();
    
    foreach($keys as $key)
    {
        if(isset($array[$key]) && !empty($array[$key])) $use_in_query[$key] = $array[$key];
    }
    
    Now you can use the $use_in_query var in your query.
    
    $dbh->execute($use_in_query);
    

    [/编辑]

    【讨论】:

    • 我明白了,所以与其写出每个 if isset,不如把它放在一个 foreach 循环中?
    • 没错。也许您甚至已经定义了字段,您可以使用它们而不是重新定义它们。
    猜你喜欢
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多