Guitar2018
Guitar2018

Reputation: 1

Displaying data from a database using a search query

<form action="result.php" method="POST">
    <h1>Search</h1>
    <input type="text" name="q"></input><br /><br />
    <input type="submit" id="submit" value="Search"></input>
  </form>    

form

<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$mysqli->set_charset("utf8");
if (isset($_REQUEST['q'])){
$target= $_REQUEST['q'];
$sql = " SELECT *
         FROM TABLE1
         WHERE name
         LIKE '%$target%'";

  $result = $mysqli->query($sql)
  or die($mysqli->error . "<pre>$sql</pre>");
  while ($row = $result->fetch_assoc()){
    echo $row["number"] . " " . $row["name"]. " " . $row["hp"] . "<br>";
    }
} 
else {
    echo "0 results";
}
?>

result.php

Trying to use a search query to display data from the database. When the user submits the form nothing displays on the next page, not even the else. Unsure what's wrong and I'm struggling to find help in other threads. Thanks.

Upvotes: 0

Views: 37

Answers (1)

ryantxr
ryantxr

Reputation: 4217

Your script is crashing because you are using two different variables for the mysqli connection.

<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydb";

// Create connection
/* was $conn */ 
$mysqli = new mysqli($servername, $username, $password, $dbname);
// Check connection

// change $conn tp $mysqli
if ($mysqli->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$mysqli->set_charset("utf8");
if (isset($_REQUEST['q'])){
    $target= $_REQUEST['q'];
    $sql = " SELECT *
     FROM TABLE1
     WHERE name
     LIKE '%$target%'";

    $result = $mysqli->query($sql)
        or die($mysqli->error . "<pre>$sql</pre>");
    while ($row = $result->fetch_assoc()){
        echo $row["number"] . " " . $row["name"]. " " . $row["hp"] . "<br>";
    }
} 
else {
    echo "0 results";
}
?>

Upvotes: 1

Related Questions