我正在使用 for 循环创建 n 个准备好的语句,并递增这些语句中的数字。我在使用这些数字的查询时遇到问题。 Last1 是上次运行时使用的最大数字 + 1,last 2 是我们这次将使用的最大数字。这是循环和查询:
$last1 = 102;//these are normally pulled from the db, but I am specifying them here
$last2 = 104;//they are being pulled correctly, I already checked. I even tried it with specifying the variables, like this, same result.
for($i = 1; $i <= $n; $i++){
$q[$i] = "INSERT INTO outboundApps (fk_outboundAppKey, name, browser, fk_urls, fk_routes, virtualPlatform, autoAnswer, fk_GET, fk_callRates)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt[$i] = mysqli_prepare($con, $q[$i]) or trigger_error(mysqli_error($con), E_USER_ERROR);
$stmt[$i]->bind_param("issiisiis", $last1, $arr[$i][$x]/*name*/, $arr[$i][$x=$x+1]/*type/browser*/, $last1, $last1, $arr[$i][$x=$x+2]/*virtual platform*/, $d = 1, $last1, $arr[$i][$x=$x+3]/*call rates*/);
$x = $x+4;
$last1++;
}
为了将其添加到数据库中,我只需对数组 $stmt[] 执行一个 for 循环。理论上,当执行此操作时,我应该将类似以下内容添加到数据库中:
102, Out 1, XML, 102, 102, default, 1, 102, rate1
103, Out 2, HTML, 103, 103, default, 1, 103, rate2
相反,当两行添加到数据库时,它们看起来像这样:
104, Out 1, XML, 104, 104, default, 104, rate1
104, Out 2, HTML, 104, 104, default, 104, rate2
有什么想法为什么会发生这种情况吗?最后执行语句时,是否使用last1的最终值,而不是准备语句时last1的值?
edit3:我删除了 $n,整个过程通过 $i 递增,但这仍然不是问题的重点。
最佳答案
bind_param
在执行查询时将参数绑定(bind)到查询。每当执行 $stmt[$n]
时,它都会使用当时的参数。循环运行后,$last1
是最后一个值,任何执行都将使用该值。
更简单的方法是同时循环和执行。
关于php - 准备好的语句中的数字发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20954422/