doujiao7325 2016-12-23 10:51
浏览 178
已采纳

在php中将关联数组插入MySQL数据库

I have an array called $output which contains:

Array
(
    [0] => Array
        (
            [0] => J Arora
            [1] =>  India
        )

    [1] => Array
        (
            [0] => J Ramuj
            [2] =>  Russia
        )

    [2] => Array
        (
            [1] =>  KJ Tris
            [2] =>  Germany
        )

)

How can i insert these data into mysql database table like these

---------------
name   | country
-------|---------
J Arora|India
-------|--------
J Ramuj|Russia
-------|--------
KJ Tris|Germany
-------|--------

I am not able to fetch these values separately from given array as their index are not in sequence.

  • 写回答

5条回答 默认 最新

  • duanhuan2301 2016-12-23 10:58
    关注

    Just loop it with a foreach, and use PHP native functions like current() and end() to get your elements. Given that you just have two elements in your array at all times, this should work

    foreach ($output as $v) {
        echo current($v); // Name
        echo end($v); // Country
    }
    

    Adapt this to build your query and execute it inside the loop. Inside the loop you could do

    foreach ($output as $v) {
        $sql = "INSERT INTO table (`name`, `country`) VALUES ('".current($v)."', '".end($v)."')";
        // TODO: Execute query
    }
    

    You should also note that any query using variables should be using prepared statements with placeholders. Both MySQLi and PDO supports this.


    Using prepared statements

    Build the query before, and execute it as you loop it with the appropriate variables bound.

    Example with PDO:

    $stmt = $pdo->prepare("INSERT INTO table (`name`, `country`) VALUES (:name, :country)");
    foreach ($output as $v) {
        $stmt->execute(array("name" => current($v), "country" => end($v));
    }
    

    Example with MySQLi:

    $stmt = $mysqli->prepare("INSERT INTO table (`name`, `country`) VALUES (?, ?)");
    foreach ($output as $v) {
        $name = current($v);
        $country = end($v);
        $stmt->bind_param("ss", $name, $country);
        $stmt->execute();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 脱敏项目合作,ner需求合作
  • ¥15 脱敏项目合作,ner需求合作
  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密