Search code examples
phphtmlmysqlsearchsql-like

Search MySQL database with LIKE statement


I need to return search results of users in my database.

At the moment, I have managed to use the LIKE function in the MySQL query to return a results count, but I need it to echo the usernames of all the results, not just the first result:

<?php
    // mysql details
    $host="localhost"; // Host name 
    $username="classified"; // Mysql username 
    $password="classified"; // Mysql password 
    $db_name="jaycraftcommunity"; // Database name 
    $tbl_name="members"; // Table name 

    // Connect to server and select database.
    mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
    mysql_select_db("$db_name")or die("cannot select DB");

    // form variable to local
    $search = $_POST['username'];

    // make query
    //$sql = "SELECT * FROM $tbl_name WHERE (username='$search' OR verified='$search')"; // sql query
    $sql = "SELECT username FROM $tbl_name WHERE username LIKE '%$search%'"; // sql query
    $result = mysql_query($sql); // do query

    // handle query data
    $count = mysql_num_rows($result);
    $row = mysql_fetch_row($result);
    $array = mysql_fetch_array($result);

    echo $count;

    foreach( $row as $arrays ): ?>
    <tr>
        <td><?php echo htmlspecialchars( $arrays ); ?></td>
        <br />
    </tr>
<?php
    endforeach;
?>

The HTML form looks like this:

<h2>Search</h2>

<form method="post" action="search_engine.php">
    Search for:
    <input type="text" name="username">
    <input type="submit" value="Search for username">
</form>

At the moment, if you go to http://dev.jaycraft.co/player/dupe/search.php you can see it in action. Search for individual letters, it show how many results there are with echo $count, but only echos the first result.

Thanks


Solution

  • Every call of mysql_fetch_row($result) will return another row and advance the cursor. You simply need to use a while() to loop over all rows in the result:

    while($row = mysql_fetch_row($result)) {
        echo $row[0];
    }}
    

    For ease of use, it's better to use mysql_fetch_assoc($result); which will return an associative array:

    while($row = mysql_fetch_assoc($result)) {
        echo $row['username'];
    }}