Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a PHP variable into an SQL query [duplicate]

Tags:

sql

php

select

I have an SQL query

qry1 = 
"SELECT DISTINCT (forename + ' ' + surname) AS fullname
FROM users
ORDER BY fullname ASC";

This gets forename and surname from a table called users and concatenates them together, putting a space in the middle, and puts in ascending order.

I then put this into an array and loop through it to use in a select drop-down list.

This works, however, what I now want to do is compare the fullname with a column called username in another table called users.

I'm struggling with how to write the query though. So far I have...

$qry2 
"SELECT username 
FROM users 
WHERE (forename + ' ' + surname) AS fullname 
=" . $_POST['Visiting'];

Any advice on to what I am doing wrong?

like image 278
ginomay89 Avatar asked May 28 '26 03:05

ginomay89


1 Answers

Rather CONCAT the two columns together. Also remember to escape any variables before adding them to your query.

$qry2 =
"SELECT username AS fullname
FROM users 
WHERE CONCAT(forename, ' ', surname)
='" . mysqli_real_escape_string($connection, $_POST['Visiting']) . "'";

Where $connection is your current db connection

like image 181
shauns2007 Avatar answered May 31 '26 05:05

shauns2007