Search code examples
phpmysqlselectsql-like

Select rows based on textarea value


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>";
}

Solution

  • 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.