添加多个sql查询的结果

myss37ts  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(346)

我正在尝试添加3个sql查询的结果。所有3个查询都返回整数值。
如何将3个sql查询的结果添加到一个变量中并进行回显?代码:

<?php
define('HOST','mywebsite.com');
define('USER','username');
define('PASS','password');
define('DB','imagebase');
$con=mysqli_connect(HOST,USER,PASS,DB);
if($_SERVER['REQUEST_METHOD']=='POST'){
    $val1=$_POST['sval1'];
    $val2=$_POST['sval2'];
    $val3=$_POST['sval3'];
    $sql="select price from images where name='$val1'"; //returns 100
    $sql1="select price from images where name='$val2'"; //returns 100
    $sql2="select price from images where name='$val3'"; //returns 100
    $result=mysqli_query($con,$sql);

    $count=mysqli_num_rows($result);
    $result1=mysqli_query($con,$sql1);

    $count1=mysqli_num_rows($result1);
    $result2=mysqli_query($con,$sql2);

    $count2=mysqli_num_rows($result2);

    if ($count==1) {
        $res1=$count;
    } 
    if ($count1==1) {
        $res2=$count;
    } 
    if ($count2==1) {
        $res3=$count;
    } 

    $final=$res1+$res2+$res3;  //should return 300 but returns 3
    echo $final;

    mysqli_close($con);

} else {
    echo 'Error Updating Price';
    mysqli_close($con);
}
?>
vuktfyat

vuktfyat1#

在if语句中,您忘记了更改 $count$count1 以及 $count2 在第二次和第三次陈述中。另外,你确定要检查吗 $count, $count1, $count2 等于1?您可能需要检查这些变量是否有错误值 if($count) 之后,你需要初始化 $res1, $res2, $res3 在if语句之前设置为0,否则可能会导致以后求和时出错 $res 之前由于falsy if语句而未初始化的变量。

rt4zxlrg

rt4zxlrg2#

有问题的警告代码易受sql注入攻击!别这样。任何包含在sql文本中的潜在不安全值都必须正确转义。首选的模式是将准备好的语句与绑定占位符一起使用。
为了解决被问到的具体问题:我们需要 fetch 行,并累积为price返回的值。
看起来我们并不关心返回的行数;所以没有理由调用num\u rows函数。

$tot = 0;

$result=mysqli_query($con,$sql);
while( $row = $result->fetch_assoc() ) {
    $tot += $row['price'];
}

$result1=mysqli_query($con,$sql1);
while( $row = $result1->fetch_assoc() ) {
    $tot += $row['price'];
}

$result2=mysqli_query($con,$sql2);
while( $row = $result2->fetch_assoc() ) {
    $tot += $row['price'];
}

echo "tot = " . $tot;

但是为什么要运行三个独立的查询呢?如果我们想要的是一个总数,我们可以让mysql来计算。
而且,面向对象模式比过程模式简单得多。

$sql = 'SELECT SUM(i.price) AS tot_price
          FROM images i
         WHERE i.name IN ( ? , ? , ? )';

if( $sth = $con->prepare($sql) ) { 
   $sth->bind_param('sss',$val1,$val2,$val3);
   if( $sth->execute() ) {
       $sth->bind_result($tot_price);
       if( $sth->fetch() ) {
          echo "tot_price = " . $tot_price;
       } else {
         // no row returned 
       }
       $sth->close(); 
   } else {
      // handle error in execute
} else {
   // handle error in prepare
}

相关问题