我有一个看起来像
的数据库COUNTRY RATES
AUD 0.5
BRL 1.2
CAD 1.6
CHF 1.4
CZK 2.5
现在我想使用此数组更新费率
$rates = array (
'AUD' => '0.5',
'BRL' => '6.2',
'CAD' => '2.6',
'CHF' => '7.4',
'CZK' => '1.5',
);
我尝试使用此代码
$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';
$values = "'" . implode("','", array_values($rates)) . "'";
$sql = "UPDATE `eurotoforgein` SET 'RATES' WHERE rates = $values";
if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $conn->error . ']');
}
else{
echo "Data Updated.";
}
但是我明白了 运行查询时出错[您的SQL语法中有错误;查看与您的MariaDB服务器版本相对应的手册,以便在''RATES'附近使用正确的语法'WHERE rates ='0.5','1.2','1.6','1.4','2.5''在第1行
欢迎任何帮助
答案 0 :(得分:2)
这是我的解决方案:
$sql = '';
$rates = array (
'AUD' => '0.5',
'BRL' => '6.2',
'CAD' => '2.6',
'CHF' => '7.4',
'CZK' => '1.5',
);
$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);
}
foreach($rates as $iso=>$rate){
$sql .= "UPDATE `eurotoforgein` SET `RATES`='{$rate}' WHERE COUNTRY = '{$iso}'";
}
if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $conn->error . ']');
}else{
echo "Data Updated.";
}
答案 1 :(得分:1)
您必须逐个更新这些值。这应该会帮助你:
foreach ($rates as $country => $rate) {
$sql = "update rates set RATES = $rate where COUNTRY = $country";
// execute
}
如果您想了解更多信息,请查看UPDATE语法:http://dev.mysql.com/doc/refman/5.7/en/update.html
答案 2 :(得分:0)
你的SQL查询是这样的:
UPDATE `eurotoforgein` SET 'RATES' WHERE rates = '0.5','6.2','2.6','7.4','1.5'
这不是有效的SQL。
以这种方式构建查询:
$sql = '';
foreach($rates as $country => $value){
$sql .= "UPDATE `eurotoforgein` SET `rates` = '$value' WHERE `country` = '$country';";
}
这将创建一个包含多个UPDATE查询的字符串,并且可以在
中执行1 go,$ conn-> query($ sql);