PHP / mySQL - for循环无法正常工作

时间:2015-10-20 22:22:15

标签: php mysql

我有这些代码行:

$user = $_SESSION['name'];
$con = mysqli_connect("localhost","root","","db_shop");
$sql = mysqli_query($con,"SELECT * FROM tbl_cart WHERE `user` = '$user' AND `done` = '0'");

while( $result = mysqli_fetch_assoc( $sql ) ){

    $file = $result['items'];
    $res = explode(",",$file);
    $total = 0;
    $tmp = count( $res );
    for( $i = 0 ; $i <= $tmp; $i++ ){

        $sql = "SELECT * FROM `tbl_details` WHERE `file_name` = '".$res[$i]."'";
        echo $sql;
        $sql = mysqli_query( $con, "SELECT * FROM `tbl_details` WHERE `file_name` = '".$res[$i]."'");
        while( $res = mysqli_fetch_assoc( $sql ) ){
            $total += $res['price'];
        }
        echo "<script>alert('$total');</script>";
    }
}

其中$res[1]必须包含我的数据库中1000的值,但它只给我一个null值。

正如您所看到的,我尝试echo $sql $res[0]$res[1]返回了正确但SELECT * FROM `tbl_details` WHERE `file_name` = '' 返回的内容:

public class Metrics {
    AtomicLong sent = new AtomicLong();
    AtomicLong totalElapsedMsgTime = new AtomicLong();

    AtomicLong sentLastSecond = new AtomicLong();
    AtomicLong avgTimeLastSecond = new AtomicLong();

    public void outTick(long elapsedMsgTime){
        sent.getAndIncrement();
        totalElapsedMsgTime.getAndAdd(elapsedMsgTime);
    }

    class CalcMetrics extends TimerTask {
       @Override
        public void run() {
            sentLastSecond.set(sent.getAndSet(0));
            long tmpElapsed = totalElapsedMsgTime.getAndSet(0);
            long tmpSent = sentLastSecond.longValue();

            if(tmpSent != 0) {
                avgTimeLastSecond.set(tmpElapsed / tmpSent);
            } else {
                avgTimeLastSecond.set(0);
            }
        }
    }
}

感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

我想知道是否因为内部sql语句引用了相同的变量名hiddenRecaptcha: $("#g-recaptcha-response").val(), ?更改了内部变量名....

$sql

答案 1 :(得分:0)

您应该将$i <= $tmp更改为$i < $tmp

因为count $tmp = count( $res );返回元素数但不返回元素的最大索引。

for( $i = 0 ; $i < $tmp; $i++ ){

在这里你应该使用另一个变量名而不是$res

    while( $row = mysqli_fetch_assoc( $sql ) ){
        $total += $row['price'];
    }