I'm using a PDO to run this query, is there a way to see if the query return false? and why my query return nothing when I expect a result?
$selectsql = "SELECT `firstname`,`surname`,`phone`,`address`,`username`,`StudentID` FROM `student_info` WHERE ? LIKE ?";
$selectstmt = $conn->prepare($selectsql);
$selectstmt->execute(array($searchby,"%{$searchval}%"));
while($data = $selectstmt->fetch(PDO::FETCH_ASSOC)){
echo "
<tr>
<td>{$data['firstname']}</td>
<td>{$data['surname']}</td>
<td>{$data['phone']}</td>
<td>{$data['address']}</td>
<td>{$data['username']}</td>
<td>Delete Account</td>
</tr>
";
var_dump($data);
}
I var dumpped the $searchby
and the $searchval
and they seems fine to me, no mistype or whatsoever.
The problem with your query is here :
$selectsql = "SELECT firstname`,`surname`,`phone`,`address`,`username`,`StudentID` FROM `student_info` WHERE ? LIKE ?";
That placeholder after where
is messing up your query, after the where clause there should be a column name, by the way I see $searchby
changes based on the item selected by the user.
One thing you should note is that :
Table and Column names cannot be replaced by parameters in PDO.
Your query should look like.
<?php
$search = "%".$searchval."%";
$selectsql = "SELECT `firstname`,`surname`,`phone`,`address`,`username`,`StudentID` FROM `student_info` WHERE $searchby LIKE ?";
$selectstmt = $conn->prepare($selectsql);
$selectstmt->execute([$search]);
$results = $selectstmt->fetch((PDO::FETCH_ASSOC));
if(count($results) > 0){
var_dump($results);
foreach($results as $data):?>
<tr>
<td><?php echo $data['firstname'];?></td>
<td><?php echo $data['surname'];?></td>
<td><?php echo $data['phone'];?></td>
<td><?php echo $data['address'];?></td>
<td><?php echo $data['username'];?></td>
<td>Delete Account</td>
</tr>
<?php
endforeach;
}else{
echo "no results found";
}
?>