i am trying to build a small search tool for a single table of a mySQL Database. Sadly i can't bind my function parameter to my sql statement and i can't figure out why.
This is how i think it works.(maybe you can spot a mistake in my general approach)
- At first the parameter ($field) get passed to the function by referencing it inside the function call at the bottom of the file.
- I am referencing the paramter key of $field (:field) inside the $dbh->prepare() statement.
- The variable $field is bound as a Parameter with $query->bindParam()
- The query is being executed
- $field is used to extract the title from the modified query.
I already figured out that the problem only occurs when i try to bind the parameter to the statement. So somewhere between step 2-4.
Whenever i insert the $field as a pure string (as "title" into step 2+5) everythings works fine. But thats not very dynamic and therefore i can't use the functions parameter.
Is there someone out there who could give me a hint :) ? I am thankfull for any help.
<?php
// establish connection to database
$dbh = new PDO($server, $user, $pass);
/* function takes PDO object and a string that defines the column of our table that is supposed to be returned */
function searchField($dbh,$field){
if(isset($_POST['searchbar'])){
$searchInput = $_POST['searchbar'];
$searchInput = "%" . $searchInput . "%";
// (2)
$query = $dbh->prepare('SELECT * FROM docs WHERE :field LIKE :searchInput');
// (3)
$query->bindParam(':field',$field);
$query->bindParam(':searchInput',$searchInput);
// (4)
$query->execute();
foreach ($query as $doc){
// (5)
return $doc[$field];
}
}
}
?>
<form action="index.php" method="post" class="search-form">
<div class="searchbar-container">
<input class="searchbar" name="searchbar" placeholder="Enter a filename..."></input>
<button class="btn btn-default search-button " type="submit"><span class="glyphicon glyphicon-search submit-search" aria-hidden="true"></span></button>
</div>
</form>
<div class="result-title-container">
<?php
// (1) ==== The function call ====
echo "<h4>" . searchField($dbh,"title") . "</h4>";
?>
</div>