Home > Software design >  PHP not printing the data from table
PHP not printing the data from table

Time:01-31

I'm currently facing a problem that I don't know how to solve, basically, I have two files in one of them I have this form:

<body>
  <form action="getuser.php" method="GET">
    <input id="search-button" name="search" type="text" placeholder="Type here">
    <input id="submit-button" name="submit" type="submit" value="Search">
  </form>
</body>

And this would be the "getuser.php":

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "assinaturas";
$search = "";

if(isset($_GET['search'])):
  $search = $_GET["search"];
endif;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, name, title, doc, tel, add FROM `info` WHERE id = '%".$search."%'";
$result = $conn->query($sql);


while($row = $result->fetch_assoc()) {
  echo "<p>" . $row["name"] . "</p>";
  echo "<p>" . $row["title"] . "</p>";
  echo "<p>" . $row["doc"] . "</p>"; 
  echo "<p>" . $row["tel"] . "</p>";
  echo "<p>" . $row["add"] . "</p>";
}
 
$conn->close();
?>

And the problem is, when I submit the form I get a blank screen as a result. Can someone please help? I don't have any ideia of how to solve this! Thanks for the attetion.

CodePudding user response:

I think you got no results from the database because of the incorrect sql.

If you want an exact match then remove the % next to $search.

$sql = "SELECT id, name, title, doc, tel, add FROM info WHERE id = '$search'";

Otherwise, you should use LIKE instead of = in your SQL WHERE statement.

$sql = "SELECT id, name, title, doc, tel, add FROM info WHERE id LIKE '%$search%'";

CodePudding user response:

This works fine, as I tried with PHP 8.2 and Apache HTTP Server 2.4. Note that I am using the Prepared statement and passing the search string as parameter to it.

...
$sql = "SELECT id, name, title, doc, tel, add FROM info WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->execute([ $search ]);
$result = $stmt->get_result();

//print_r($result);

echo "<h1>Results: </h1>";

while($row = $result->fetch_assoc()) {
    ...
  • Related