使用mysqli将多维数组转换为db

时间:2013-05-02 21:47:22

标签: php multidimensional-array mysqli

我有一个很长的数组$ price,结构如下

Array
(
    [Fund] => BGEF
    [Class] => G
    [Currency] => CAD
    [NAV] => 8.6442
    [NavChange] => 0.0431
    [PriceDate] => 2013-05-01
)
Array
(
    [Fund] => BGOF
    [Class] => G
    [Currency] => EUR
    [NAV] => 12.1503
    [NavChange] => 0.0226
    [PriceDate] => 2013-05-01
)
Array
(
    [Fund] => BIEF
    [Class] => G
    [Currency] => USD
    [NAV] => 9.6914
    [NavChange] => 0.0635
    [PriceDate] => 2013-05-01
)

我想把它放到一个用相应的行创建的mysql表中。 fund_id,类别,货币,资产净值,nav_change,price_date

这是我最近尝试将行插入多个数据库行

    $mysqli = new mysqli( "localhost", "user", "pw","db" );
    if( $mysqli->connect_errno ){
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }
    $mysqli->select_db("db");
                foreach($prices as $rows){                      
                        $sql = "  INSERT INTO price_data(  price_date,fund_id,currency_id,class_id,nav,nav_change  ) 
                            VALUES (  $rows[PriceDate] , $rows[Fund] , $rows[currency] , $rows[Class] , $rows[NAV] , $rows[NavChange]  )   " ;

    $stmt = $mysqli->prepare($sql);
    $stmt->execute();

     }

目前这会返回一个致命错误:在非对象上调用成员函数execute()。我不清楚(显然)使用mysqli方法的一些事情,比如循环的去向,以及这是访问数据的正确类型。

任何帮助都会很棒,谢谢。

1 个答案:

答案 0 :(得分:2)

您的代码存在一些问题。

  1. 您没有正确使用数组语法
  2. 在您的查询中,需要引用非数字值
  3. 您正在多次查询数据库,这是没有必要的
  4. 我没有您的数据库,因此以下代码未经过任何方式的测试。阅读评论并尝试理解代码:

    // Connect to the database as usual
    $mysqli = new MySQLi("localhost", "user", "pw", "db");
    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: ({$mysqli->connect_errno}) {$mysqli->connect_error}";
    }
    // The first part of the SQL query
    $query = "INSERT INTO `price_data` (`price_date`, `fund_id`, `currency_id`, `class_id`, `nav`, `nav_change`) VALUES";
    
    // This is the format of a VALUES tuple; it is used
    // below in sprintf()
    $format = " ('%s', '%s', '%s', '%s', %f, %f),";
    
    // Go over each array item and append it to the SQL query
    foreach($prices as $price) {
        $query .= sprintf(
            $format,
            $mysqli->escape_string($price['PriceDate']),
            $mysqli->escape_string($price['Fund']),
            $mysqli->escape_string($price['Currency']),
            $mysqli->escape_string($price['Class']),
            $mysqli->escape_string($price['NAV']),
            $mysqli->escape_string($price['NavChange'])
        );
    }
    // The last VALUES tuple has a trailing comma which will cause
    // problems, so let us remove it
    $query = rtrim($query, ',');
    
    // MySQLi::query returns boolean for INSERT
    $result = $mysqli->query($query);
    
    // Find out what happened
    if ($result == false) {
        die("The query did not work: {$mysqli->error}");
    } else {
        die("The query was a success!");
    }