[英]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. 我在我的php页面中使用这些查询,我认为有一种更好的方法可以做同样的事情。
$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. 我想我可以通过在查询中使用AS
键来获得结果,但我不知道如何。
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
使用mysql IN
select * from cms where cmsID in (1,2,3,4,5)
You can use IN clause to replace many OR conditions 您可以使用IN子句替换许多OR条件
$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 在MySQL中
SELECT * FROM cms WHERE cmsID BETWEEN 1 AND 5;
For more information on Between clause, you can visit this Link 有关between子句的更多信息,您可以访问此链接
$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."'"); for($ i = 1; $ i <= 5; $ i ++){$ cms1 = getRow(“从cms中选择*,其中cmsID ='”。$ i。“'”);
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.