准备好的声明中的数字在变化

时间:2014-01-06 16:24:13

标签: php mysql mysqli prepared-statement

我正在使用for循环来创建n个预准备语句,并在这些语句中递增一个数字。我在使用这些数字的查询时遇到问题。 Last1是上次运行时使用的最大数字+ 1,最后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

相反,将这些行添加到db:

时,这两行都是这样的
104, Out 1, XML, 104, 104, default, 104, rate1
104, Out 2, HTML, 104, 104, default, 104, rate2

为什么会发生这种情况?当语句最终执行时,它是否使用last1的最终值,而不是语句准备时的last1值?

edit3:我放弃了$ n,整个事情通过$ i递增,但这仍然不是问题的关键。

1 个答案:

答案 0 :(得分:1)

bind_param在执行时将参数绑定到查询。每当执行$stmt[$n]时,它将使用当时的参数。循环运行后$last1是最后一个值,任何执行都将使用此值。

更简单的方法就是同时循环和执行。

相关问题