I am trying to make a postgresql select query work with php, but can’t get past the syntax.
I have a variable and a query that returns the surname of any match.
$name = 'Smith'; $query = 'SELECT surname FROM emploee WHERE name= '.$name.';'; $a = pg_query(connect(),$query ); while($row = pg_fetch_array($a)){ echo "Match"; }
For those who wonder why do I have to declare Smith as a variable, $name
is not always equals to Smith. The value of $name
is taken correctly from another query. However, this is not working. I read in an article that I should use pg_query_params() but couldn’t get that to work neither.
Your help would be highly appreciated
Advertisement
Answer
These are the two methods that worked, suggested by Bang and Frank Heikens respectively. Since they only commented, I am posting it as an answer for those who might come up the same situation. However, I would strongly advise them to read the comments too. I learned a couple of stuff on the way, you might as well.
Bang’s suggestions->
$a = trim($name); $query = "SELECT surname FROM employee WHERE name= '" . $a . "';"; $result = pg_query(connect(), $query); while($row = pg_fetch_array($result)){ echo "Match"; }
Frank Heikens suggestions ->
$n = trim($name); $s = trim($surname); $params = array ($n, $s); $result = pg_query_params(connect(), 'SELECT office FROM emploee WHERE name = $1 and surname = $2', $params); while($row = pg_fetch_array($result)){ $k = $row['path']." ".$row['office']; echo $k; }
In both cases I have to use trim (not sure if this will be your case too). I added a third field office to demonstrate how can I take several arguments. If anyone has other critics, suggestions or solutions, be my guest. I will try everyone of them and let you know.