0

I have a HTML search form made with PHP that connects to a MySQL database, finds a table with columns and rows and then displays this data with an echo under the table.

$output = "Document ID: ".$results['id']."<br><a href='".$results['url']."'>".$results['name']."</a> (".$results['short_withtag'].")<be>

The columns are id, name, short, short_withtag and url. The problem is, if I enter a keyword like pie (such a term existing in all of the rows) it will display only one search result. How do I make it display more than one?

Here is the query I use:

mysql_query("SELECT * FROM env
WHERE (`id` LIKE '%".$query."%') OR (`name` LIKE '%".$query."%') OR (`short` LIKE '%".$query."%') OR (`short_withtag` LIKE '%".$query."%') OR (`url` LIKE '%".$query."%')") or die(mysql_error());
3
  • Post the MySQL query you're using. Commented Dec 22, 2016 at 22:29
  • okay, I edited my post. Commented Dec 22, 2016 at 22:34
  • You need to get the results of the query into an array and then loop through adding to your $output variable each time. You are currently just storing the first row of the result set. Commented Dec 22, 2016 at 22:37

1 Answer 1

1

Just get all rows into an array and then output them with a foreach loop.

You can do that like this:

$result = mysql_query("SELECT * FROM env
WHERE (`id` LIKE '%".$query."%') OR (`name` LIKE '%".$query."%') OR (`short` LIKE '%".$query."%') OR (`short_withtag` LIKE '%".$query."%') OR (`url` LIKE '%".$query."%')") or die(mysql_error());

// If query is successful
if ($result) {

    // Create an empty array to which we're going to put rows
    $dataForTheOutput = array();

    // Now push each row into the array
    while ($row = mysql_fetch_assoc($result)) {

        array_push($dataForTheOutput, $row);

    }

    // Now you can output data

    if (empty($dataForTheOutput)) {

        echo 'No results found';

    } else {

        // Using foreach loop display each row
        foreach ($dataForTheOutput as $component) {

            echo "Document ID: ".$component['id']."<br><a href='".$component['url']."'>".$component['name']."</a> (".$component['short_withtag'].")<br><span style='font-size: 12px;'>Bad search result? Try a different keyword</span>

        }

    }

}

Note that this is a quite obsolete and not very secure or maintainable way of doing things.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.