简体   繁体   中英

multiple sql queries into one small and better query

I am using these queries in my php page and I think there is a better way to do the same thing.

$cms1 = getRow("select * from cms where cmsID=1");
$cms2 = getRow("select * from cms where cmsID=2");
$cms3 = getRow("select * from cms where cmsID=3");
$cms4 = getRow("select * from cms where cmsID=4");
$cms5 = getRow("select * from cms where cmsID=5");

I am printing the data from these queries like

<?=$cms['content']?> 
<?=$cms2['content']?>
<?=$cms3['content']?> ....

Is there a better way to do this or to get all this data in one single query? I think I might get the result by using AS key in the query but I have no idea how.

function getRow($query)
{
    $rs = mysql_query($query) or die(mysql_error());
    $result = array();

    if(mysql_num_rows($rs))
    {
        $row = mysql_fetch_assoc($rs);      
        return $row;
    }
}

use mysql IN

select * from cms where cmsID in (1,2,3,4,5)

You can use IN clause to replace many OR conditions

$sql = "select * from cms where cmsID in (1,2,3,4,5)";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
    echo $row['cmsID'].' '.$row['content'];//output like  :- 1 content
    }

This can also be best achieved using

BETWEEN

in mysql

 SELECT * FROM cms WHERE cmsID BETWEEN 1 AND 5; 

For more information on Between clause, you can visit this Link

$arrData = array();
$result = mysql_query($query) or die(mysql_error());
while($row = $result->fetch_array()) {

    array_push($arrData,$row);
}

print_r($arrData);

First of All change your function

function getRow($query)
{

$rs = mysql_query($query) or die(mysql_error());
$result = array();
if(mysql_num_rows($rs))
 {

   while($row = mysql_fetch_assoc($rs))
   {
       $record[$row['cmsID']] = $row;
   }

 return $record;
 }
}  

Then change your query

$output = getRow(select * from cms where cmsID in (1,2,3,4,5));  

Then echo your output.

print_r($output);

for($i=1;$i<=5; $i++) { $cms1 = getRow("select * from cms where cmsID='".$i."'");

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM