Select rows based on textarea value

痴心易碎 提交于 2020-03-06 09:21:06

问题


Depending on the search pattern I need to get the data displayed from the server.

include("dbconfig.php");
$sql="select * from blog where title LIKE '{$title}%'";
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
    echo"<tr>";
        echo"<td><img src='uploads/".$row['file']."' height='150px' width='200px'</td>";
        echo"<td><h3>".$row['title']."</h3>".$row['description']."</td>";
    echo"</tr>";
}

回答1:


Here is a complete rewrite that implements mysqli as commented under the question. For security & ease of use, it uses a prepared statement with a bound parameter and bound results.

(Also notice, I've replaced the * wildcard in your SELECT. It is always good practice to only ask the database for exactly what you need.)

$db=new mysqli("localhost","username", "password","database");  // do this in your include
if($stmt=$db->prepare("SELECT `file`,`title`,`description` FROM `blog` WHERE `title` LIKE ?")){
    $search="{$_GET['title']}%";  // I assume this is passed with $_GET
    $stmt->bind_param("s",$search);
    $stmt->execute();
    $stmt->bind_result($file,$title,$description);
    while($stmt->fetch()){
        echo"<tr>";
            echo"<td><img src='uploads/{$file}' height='150px' width='200px'</td>";
            echo"<td><h3>{$title}</h3>{$description}</td>";
        echo"</tr>";
    }
    $stmt->close();
}

p.s. Typically table searches are done by using % on both sides of your LIKE value. Your search will only return results that "start with title". Please consider changing this in your code.




回答2:


Change the query like below:

$sql="select * from blog where title LIKE '".$title."%';


来源:https://stackoverflow.com/questions/43471890/select-rows-based-on-textarea-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!