我有一个看起来像
的关联数组$rates = array (
'AUD' => '0.5',
'BRL' => '1.2',
'CAD' => '0.6',
'CHF' => '0.4',
'CZK' => '1.5',
);
我想把这个数组放在mysql中,以便我可以使用这些费率来制作货币转换器。 我的问题是你怎么做我试过的
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "eurotoforgein";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$table = 'rates';
$keys = implode(', ', array_keys($rates));
$values = "'" . implode("','", array_values($rates)) . "'";
$sql = 'insert into '.$table.'('.$keys.') values ('.$values.')';
if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $conn->error . ']');
}
else{
echo "Data inserted.";
}
我得到的错误是 运行查询时出错[未知栏' AUD'在'字段列表'] 对于使用的表
// sql to create table
$sql = "CREATE TABLE eurotoforgein (
COUNTRY VARCHAR(6),
RATES FLOAT(10)
)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
欢迎任何帮助 感谢
答案 0 :(得分:0)
你可以为这样的多个值生成一个插入
$pairs = [];
foreach($rates as $key => $value)
{
$pairs[] = "('$key', $value)";
}
$pairs_str = implode(',', $pairs);
$sql = 'insert into '.$table.' (COUNTRY, RATES) values ' . $pairs_str;