Reputation: 1852
Having problems passing a parameter to a sql query if the parameter has spaces in it. The code is
$statement="select di_timestamp, di_item_value
from data_item
where
fk_fc_id=(select fc_id
from field_column
where
fc_description ilike :sensor
and
fk_mds_id=( select mds_id
from monitored_data_set
where fk_pa_id=(select pa_id
from pilot_ambient
where
pa_ambient_name ilike :room
and
fk_sp_id=(
select sp_id
from School_Pilot
where sp_description ilike :name
)
)
)
)";
$query = $databaseConn->prepare($statement);
$query->execute(array(':sensor'=>$sensor,':room'=>$room,':name' => '%'.$school.'%'));
However if sensor contains any spaces the query fails. How can I resolve this? I've tried putting quotes in the parameter, quotes in the query, but nothing works.
Upvotes: 0
Views: 430
Reputation: 61526
You may pass space characters in prepared statements parameters without quotes or any special care.
Here's a demo:
<?
$pdo = new PDO('pgsql:dbname=test');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT 1 WHERE 'abc de' ilike :pattern";
try {
$stmt = $pdo->prepare($query);
$stmt->execute(array(":pattern"=>'ABc %'));
var_dump($stmt->fetchAll());
}
catch(PDOException $e){
echo "Error". $e->getMessage();
}
?>
It yields no error and displays the proper result:
array(1) { [0]=> array(2) { ["?column?"]=> int(1) [0]=> int(1) } }
If the datatype of the column to match is of type CHAR(n)
as opposed to VARCHAR(n)
or TEXT
, be aware that trailing spaces are treated as non significant.
Upvotes: 1