以下代码适用于其他人但不适用于我

时间:2014-11-03 16:08:16

标签: php html

当我尝试在表单中搜索某些内容时,它会向我显示所有变量的错误...

<form action="search.php" method="get">
     <input type="text" size="25" name="search" placeholder="search this site">
     <input type="submit" name="submit" value="search"></form>
    <?php
     include("includes/connect.php");
      if(isset($_GET['submit'])){
       $search_id = $_GET['search'];
       $query = "select * from posts where post_title like '%search_id%'";
       $run = mysql_query($query);
      while ($row=mysql_fetch_array($run)){
       $post_id = $row['post_id'];
       $post_title = $row['post_title'];
       $post_image = $row['post_image'];
       $post_content = $row['post_content'];
     }
     ?>
      <h2>
       <a href="pages.php?id=<?php echo $post_id; ?>">
        <?php echo $post_title; ?></a>
      </h2>
     <center><img src="images/<?php echo $post_image; ?>" width="100" height="100"></center>
      <p align="justify"><?php echo $post_content; ?></p>
    <?php } ?>

我认为问题在于循环功能。但不知道如何解决这个问题......

1 个答案:

答案 0 :(得分:4)

你忘记了声明中的$ -sign:

$query = "SELECT * FROM `posts` WHERE `post_title` like '%$search_id%'";
顺便说一下:不要再使用mysql_query,不推荐使用它。请改用mysqli或PDO。 :)

你也很容易接受mysql注射。尝试转义$_GET值:mysql_real_escape_string($ _ GET [&#39; search&#39;])

此外,您在while循环中覆盖变量,因为对变量的调用在while循环之外。将这些变量放在while循环中,如下所示:

while ($row=mysql_fetch_array($run)){
    $post_id = $row['post_id'];
    $post_title = $row['post_title'];
    $post_image = $row['post_image'];
    $post_content = $row['post_content'];
?>
<h2>
    <a href="pages.php?id=<?php echo $post_id; ?>"><?php echo $post_title; ?></a>
</h2>
<center>
    <img src="images/<?php echo $post_image; ?>" width="100" height="100">
</center>
<p align="justify">
    <?php echo $post_content; ?>
</p>
<?php 
    }//<--- this one closes the while loop
    }//<--- this one closes the if statement
?>