for ($i=1;$i<5;$i++) //Loop read & save all vars from fieldform
{
if (array_key_exists('country'.$i, $_POST) == true)
{
${"country".$i} = $_POST['country'.$i];
$get_id = mysqli_query($connection, "SELECT country_id FROM country WHERE country_pl = '{$country[$i]}'");
$row = mysqli_fetch_assoc($get_id);
$country_id = $row['country_id'];
echo $country_id;
}
}
这是一个读取和循环的循环保存在表单字段中选择的国家/地区除了MYSQL QUERY之外,一切正常。我不知道如何在MySQL语句中正确编写'{$country[$i]}'
。
答案 0 :(得分:0)
不要使用变量变量,使用数组。
$country[$i] = mysqli_real_escape_string($connection, $_POST['country'.$i]);
然后你可以这样做:
$get_id = mysqlil_query($connection, "SELECT country_id FROM country WHERE country_pl = '{$country[$i]}'");
答案 1 :(得分:0)
最好每次迭代运行一个查询而不是一个查询。我建议:
$countries = array();
for ($i=1;$i<5;$i++) //Loop read & save all vars from fieldform
{
if (array_key_exists('country'.$i, $_POST))
{
$countries[] = mysqli_real_escape_string($connection, $_POST['country'.$i]);
}
}
$get_id = mysqli_query($connection, "SELECT country_id FROM country WHERE country_pl IN ('" . implode ("', '", $countries) . "')");
while ($row = mysqli_fetch_assoc($get_id)) {
$country_id = $row['country_id'];
echo $country_id;
}
理想情况下,您应该使用预先准备好的声明,但这有点棘手:请参阅Trouble binding an imploded array into a mysql prepared statement