我想检查列col
中是否存在该号码并运行mysqli_num_rows
。到目前为止,它使用以下代码:
//$conn = connection to mysql.
$row1sql = "SELECT * from chktable where col='1'";
$row2sql = "SELECT * from chktable where col='2'";
$row3sql = "SELECT * from chktable where col='3'";
$row4sql = "SELECT * from chktable where col='4'";
$query1sql = $conn->query($row1sql);
$query2sql = $conn->query($row2sql);
$query3sql = $conn->query($row3sql);
$query4sql = $conn->query($row4sql);
$num1 = mysqli_num_rows($query1sql);
$num2 = mysqli_num_rows($query2sql);
$num3 = mysqli_num_rows($query3sql);
$num4 = mysqli_num_rows($query4sql);
我根据$num
编辑其他代码。
如何缩短此代码?我可以使用for
声明吗?如果适用,我该如何使用它?或者其他任何缩短此代码的方法?
感谢。
答案 0 :(得分:2)
这将获得col值和行数,仅用于col值1,2,3,4
$query = $conn->query("SELECT col, count(*) as num FROM chktable GROUP BY col WHERE col IN (1,2,3,4);");
while($row = $query->fetch_object())
echo "Col: ".$row->col.", Num:".$row->num;
你可以在while循环中做任何你想做的检查