Skip to content
Advertisement

Search form with PDO

The below code now works but how can I make it so if no results are found it echos a message instead of blank.

I think I’ve managed to create a search query for my database. Its only a very basic search but it doesn’t seem to work for some reason. Any advice would be appreciated im still new to pdo (very new! be kind!).

Also no user submitted data is inserted into the database so I think i can rule out xss assuming its SQL inject free? Which from what I understand PDO is? plus im using a stand alone DB user with no write access.

Have replace data with xxx for security

file is called search.php

*updated to reflect changes suggested *2nd update to reflect help provided *3rd update

   <html>
<head>
</head>
<body>
<form name="frmSearch" method="post" action="search.php">
  <table width="599" border="1">
    <tr>
      <th>Keyword
      <input name="var1" type="text" id="var1">
      <input type="submit" value="Search"></th>
    </tr>
  </table>
</form>
<?php
$nameofdb = 'xxxxxx';
$dbusername = 'xxxxxxxxxxxxxx';
$dbpassword = 'xxxxxxxxxxxxx';



// Connect to MySQL via PDO
try {
$dbh = new PDO("mysql:dbname=$nameofdb;host=localhost", $dbusername, $dbpassword);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}

$var1 = str_replace(array('%','_'),'',$_POST['var1']);
if (!$var1)
{
    exit('Invalid form value: '.$var1);
}


$query = "SELECT * FROM xxxxx WHERE xxxxxx LIKE :search OR xxxxx LIKE :search";
$stmt = $dbh->prepare($query);
$stmt->bindValue(':search', '%' . $var1 . '%', PDO::PARAM_INT);
$stmt->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:n");


 $result = $stmt->fetchAll();

foreach( $result as $row ) {
    echo $row["id"];
    echo $row["title"];
}




?>

</body>
</html>

Advertisement

Answer

The problem is in the form. the method is GET but in your php you expect $_POST

So this line:

<form name="frmSearch" method="get" action="search.php">

should be:

<form name="frmSearch" method="post" action="search.php">

UPDATE

Change your code to this:

// Connect to MySQL via PDO
$dbh = new PDO("mysql:dbname=$nameofdb;host=localhost", $dbusername, $dbpassword);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$var1 = $_POST['var1'];

$query = "SELECT * FROM xxxxx WHERE xxxx LIKE :search OR xxxxx LIKE :search";
$stmt = $dbh->prepare($query);
$stmt->bindValue(':search', '%' . $var1 . '%',);
$stmt->execute();

To check if there are no line and give a message you can do it like this:

$result = $stmt->fetchAll();
if ($result) { 
    foreach( $result as $row ) {
        echo $row["id"];
        echo $row["title"];
    }
} else {
    echo 'There is nothing to show';
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement