如何使用get方法显示默认帖子?

时间:2015-05-18 17:30:25

标签: php sql database

我想从浏览器获取一个id并显示数据库中的一些图片。

如果没有" display2.php?productid ="发现,然后我想显示默认图像。

我该怎么做?

这是我的代码;

$sql = "SELECT * FROM productlist where productid=".$_GET['productid'];
$result = $mysqli->query($sql);

    while($myRow = $result->fetch_array())
    {   
      if(null !==($_GET['productid']==$myRow["productid"])){
         echo "<img src=".$myRow["productid"].">"; 
      }
      else {
         echo "<img src="SELECT productimage FROM productlist where productid = 1;">"; 
      }

    }   

现在我会更容易为你解释...... 看看这个;

  //This part works without any problem 
$sql = "SELECT * FROM productlista where productid=".$_GET['productid'];
$result = $mysqli->query($restwo);

while($myRow = $resulttwo->fetch_array())
{   
  if(null !==($_GET['productid']==$myRow["productid"])){
  echo "<img src=".$myRow["productimage"].">"; 
  }

  //This part below (that should be default) does not work...

  if (!$_GET){  
  echo "hello world"; }

2 个答案:

答案 0 :(得分:0)

Asaph指出SQL注入。你应该绑定参数(谷歌),或至少这样做:

$defaultImage = "SELECT * FROM productlist WHERE imageSrc != '' OR IS NOT NULL ORDER BY productid DESC LIMIT 1";
// run the query, get the result, create a variable with default image...
$defaultImageSrc = ''; // what you get from the query result
$_GET['productid'] = preg_replace('#[^0-9]#', '', $_GET['productid']);
$sql = "SELECT * FROM productlist where productid=".$_GET['productid'];
$result = $mysqli->query($sql);
while($myRow = $result->fetch_array()) {
    if(!$myRow['imageSrc']) $myRow['imageSrc'] = $defaultImageSrc;
    echo '<img src="'.$path.'">';
}

答案 1 :(得分:0)

如果您未设置$_GET['productid']时需要max(productid)$_GET['productid'],则可以使用三元来更改您的SQL查询

$productid = ! empty($_GET['productid']) ? " WHERE productid = ".(int)$_GET['productid'] : " ORDER BY productid DESC LIMIT 1";

$sql = "SELECT * FROM productlist".$productid
$result = $mysqli->query($sql);

    while($myRow = $result->fetch_array())
    {   
         echo "<img src=".$myRow["productimage"].">"; 

    }   

所以,如果isset($_GET['productid'])您的查询将是

SELECT * FROM productlist WHERE productid = (int)$_GET['productid'] 

但如果不是,则默认为

SELECT * FROM productlist  ORDER BY productid DESC LIMIT  1