0

我有一个冗长的数组 $prices,其结构如下

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,class,currency,nav,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方法的一些事情(显然),比如循环的去向以及这是否是访问数据的正确循环。

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

4

1 回答 1

2

您的代码有一些问题。

  1. 您没有正确使用数组语法
  2. 在您的查询中,需要引用非数字值
  3. 而且您正在多次查询数据库,这不是必需的

我没有您的数据库可供我使用,因此以下代码尚未经过任何方式的测试。阅读评论并尝试理解代码:

// 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!");
}
于 2013-05-02T22:28:03.003 回答