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

3
  • 1
    What would happen if there were no rows in the result? Commented Jan 20, 2018 at 20:50
  • Put print_r($_POST); at the top of your page to make sure you are getting post variables you expect. (and print_r($_REQUEST);) Commented Jan 20, 2018 at 20:59
  • $conn is $mysqli, but nowhere is that declared. Error reporting? Commented Jan 20, 2018 at 21:02

1 Answer 1

1

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";
}
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Good catch. Is worth mentioning that this script is vulnerable to SQL injection. I suggest the author to look into prepared statements or using PDO.

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.