2012-11-01 42 views
-2

1)我有以下(包括)从我的数据库(phprealty)与两个联合表(phprealty_propert + phprealty_prop_img)显示随机记录。代码工作没有任何问题。但是,当我将限制设置为3时,我得到2条记录,这就是为什么我将限制设置为4以便获得3条记录。我可以按原样离开吗?PHP * RAND()LIMIT x,y

2)由于我是PHP新手,你认为这个代码很脆弱,因此需要某种保护?如果是这样,请告知如何使用PHP来显示数据时保护网页。

预先感谢您。

<?php 
$pid = 3; 
$myConnection = new mysqli("localhost", "root", "", "phprealty"); 
$sqlCommand = "SELECT phprealty_property.*, phprealty_prop_img.p_id, phprealty_prop_img.fn FROM phprealty_property INNER JOIN phprealty_prop_img ON phprealty_property.id = phprealty_prop_img.p_id WHERE phprealty_prop_img.def='1' AND phprealty_property.type = $pid"; 
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error()); 

$sqlCommand .= " ORDER BY RAND() LIMIT 0,4"; 
$result = mysqli_query($myConnection, $sqlCommand); 

$Displayproperty = ''; 
$row = mysqli_fetch_array($result); 
$id = $row["id"]; 
$title = $row["title"]; 
while ($row2 = mysqli_fetch_array($result)){ 
$img = $row2["fn"]; 
$thumb = 'th_' . $img; 
$Displayproperty .= ' 
<div class="random"> 
<a href="display.php?id=' . $id . '"><img src="../falcon/listImgs/' . $thumb . '" /> </a></div>'; 
} 
+1

您正在返回4行有,但第一行用于$ row变量,其余的都在$ 2行变量使用。 ORDER BY RAND()也是非常低效的操作,除非绝对必要,通常应该避免。 – CodePB

+0

感谢您的回复。但是当我将它限制为6时,我得到了6. – Omar

+0

也许我错过了一些东西,然后限制0,4应该返回4行。 – CodePB

回答

1

只要删除

$row = mysqli_fetch_array($result); 

然后改变这两条线

$id = $row["id"]; 
$title = $row["title"]; 

$id = $row2["id"]; 
$title = $row2["title"]; 

状态把两条线换货。

在您的代码中,display.php将始终显示相同的代码,因为$ id不会更改。

你的代码是否正常工作? mysqli_query上的第一个参数应为$ sqlCommand,而不是$ myConnection

如果可以,请尽量不要在Mysql上使用root/empty_password。

希望它能帮助,

+0

太棒了!它的工作就像一个魅力!但是,我不必在'$ myConnection'和'$ sqlCommand'之间切换。非常感谢 :) – Omar

相关问题