PDO with parameters

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();

Give it a run and see. :wink:

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.

I dont think its working the, heres the result when I searched for Rack #2


but since

	$search = strtolower($_GET['Search']);
	$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"';
   $query = $pdo->prepare($sql);
   $query->bindValue(':search', "'%' . $search . '%'");
   
 echo $sql;

Shouldnt the output of the query show Rack #2 instead of :search?

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.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.