更短的PHP脚本

时间:2014-01-10 23:31:24

标签: php sql loops mysqli

我需要你帮我缩短这段代码。它完美无缺。所以我不仅需要一种更短的方式,而且需要一种像这样的方式。我是PHP的新手,我知道必须有一个更短的方式来放置这个脚本。这是:

<?php $sqlMS = "SELECT * FROM Visits WHERE Company_ID = $cid AND MONTH(Date_Entered) = '1'";
$queryMS = mysqli_query($connection ,$sqlMS);
    $AdvisoryMS = mysqli_num_rows($queryMS);


$sqlMS2 = "SELECT * FROM Visits WHERE Company_ID = $cid AND MONTH(Date_Entered) = '2'";
$queryMS2 = mysqli_query($connection ,$sqlMS2);
    $AdvisoryMS2 = mysqli_num_rows($queryMS2);

$sqlMS3 = "SELECT * FROM Visits WHERE Company_ID = $cid AND MONTH(Date_Entered) = '3'";
$queryMS3 = mysqli_query($connection ,$sqlMS3);
    $AdvisoryMS3 = mysqli_num_rows($queryMS3);

$sqlMS4 = "SELECT * FROM Visits WHERE Company_ID = $cid AND MONTH(Date_Entered) = '4'";
$queryMS4 = mysqli_query($connection ,$sqlMS4);
    $AdvisoryMS4 = mysqli_num_rows($queryMS4);

$sqlMS5 = "SELECT * FROM Visits WHERE Company_ID = $cid AND MONTH(Date_Entered) = '5'";
$queryMS5 = mysqli_query($connection ,$sqlMS5);
    $AdvisoryMS5 = mysqli_num_rows($queryMS5);

$sqlMS6 = "SELECT * FROM Visits WHERE Company_ID = $cid AND MONTH(Date_Entered) = '6'";
$queryMS6 = mysqli_query($connection ,$sqlMS6);
    $AdvisoryMS6 = mysqli_num_rows($queryMS6);


$sqlMS7 = "SELECT * FROM Visits WHERE Company_ID = $cid AND MONTH(Date_Entered) = '7'";
$queryMS7 = mysqli_query($connection ,$sqlMS7);
    $AdvisoryMS7 = mysqli_num_rows($queryMS7);


$sqlMS8 = "SELECT * FROM Visits WHERE Company_ID = $cid AND MONTH(Date_Entered) = '8'";
$queryMS8 = mysqli_query($connection ,$sqlMS8);
    $AdvisoryMS8 = mysqli_num_rows($queryMS8);


$sqlMS9 = "SELECT * FROM Visits WHERE Company_ID = $cid AND MONTH(Date_Entered) = '9'";
$queryMS9 = mysqli_query($connection ,$sqlMS9);
    $AdvisoryMS9 = mysqli_num_rows($queryMS9);


$sqlMS10 = "SELECT * FROM Visits WHERE Company_ID = $cid AND MONTH(Date_Entered) = '10'";
$queryMS10 = mysqli_query($connection ,$sqlMS10);
    $AdvisoryMS10 = mysqli_num_rows($queryMS10);


$sqlMS11 = "SELECT * FROM Visits WHERE Company_ID = $cid AND MONTH(Date_Entered) = '11'";
$queryMS11 = mysqli_query($connection ,$sqlMS11);
    $AdvisoryMS11 = mysqli_num_rows($queryMS11);


$sqlMS12 = "SELECT * FROM Visits WHERE Company_ID = $cid AND MONTH(Date_Entered) = '12'";
$queryMS12 = mysqli_query($connection ,$sqlMS12);
    $AdvisoryMS12 = mysqli_num_rows($queryMS12);

2 个答案:

答案 0 :(得分:2)

使用单个查询可以极大地提高代码的效率:

$query = "SELECT MONTH(Date_Entered) AS month, COUNT(*) AS total FROM Visits WHERE Company_ID = $cid GROUP BY MONTH(Date_Entered)";

$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
   $AdvisoryMS[$row['month'] = $row['total'];
}

答案 1 :(得分:-1)

for ($i = 1; $i <= 12; $i++) {

$sql = "SELECT * FROM Visits WHERE Company_ID = $cid AND MONTH(Date_Entered) = '$i'";
$query = mysqli_query($connection ,$sql);
$AdvisoryMS[$i] = mysqli_num_rows($query);

}

这使用for循环来循环$i到1-12并将行数放在一个数组而不是12个单独的变量中。对于每个结果,您都可以通过$AdvisoryMS[1-12]

访问它们