I have a PHP/MySQL site and am trying to see if my search fuvtion works.
Heres the query which uses a parameter
SELECT rack_id,racks.name,manufacturer,model,created_date,columns.name AS colName,room_id,bays.name AS bayName FROM racks INNER JOIN rack_types ON racks.rack_type_id = rack_types.rack_type_id INNER JOIN bays ON racks.bay_id = bays.bay_id INNER JOIN columns ON bays.column_id = columns.column_id WHERE racks.name = :search
Am I doing this right?
$sql = 'SELECT rack_id,racks.name,manufacturer,model,created_date,columns.name AS colName,room_id,bays.name AS bayName
FROM racks
INNER JOIN rack_types ON racks.rack_type_id = rack_types.rack_type_id
INNER JOIN bays ON racks.bay_id = bays.bay_id
INNER JOIN columns ON bays.column_id = columns.column_id
WHERE racks.name = :search';
echo $sql;
$query = $pdo->prepare($sql);
$query->bindValue(':search', "'%' . $search . '%'");
echo $sql;
$query->execute();
From the outset it looks almost right, I think your concatenation of the search term should probably be "%$search%"
The way you have it now you would get a search term of '%'myterm'%' which would not be right and probably not what you are looking for with the single quotes in there.
Did you notice this comment? Your code still seems to be adding single-quotes in, which are generally not needed with prepared statements, and will cause a problem here.
No, that’s not how prepared statements work, they’re not just doing some other way of concatenating the variable into the query string.