MillerMedia
MillerMedia

Reputation: 3671

Syntax Help for Query

I'm trying to query my MySQL database to get information about a user. You submit a form on a previous page and then you go into the page and connect to the database and all that good stuff. I just have a quick question on syntax for the SELECT function for a query. I'm trying to say "select from tbl_name where the field first name concatenated with the field last name (with a space in between) equals the variable $user.

I figured with PHP I need to put slashes in front of the quotation marks. It doesn't seem to return any value though. Am I just using incorrect syntax?

$user=$mysqli->real_escape_string($_POST['user']);

$sql="SELECT * FROM tbl_name WHERE firstname.\" \".lastname='$user'";

Upvotes: 0

Views: 38

Answers (2)

Arun Killu
Arun Killu

Reputation: 14233

i think it is this what you are looking for??

$sql = 'SELECT * FROM '.$tbl_name .' WHERE CONCAT(firstname," ",lastname )='.$user.' ';

Upvotes: 1

newfurniturey
newfurniturey

Reputation: 38416

You will have to use SQL's CONCAT() in your WHERE clause to join the firstname and lastname columns together:

SELECT
    *
FROM
    tbl_name
WHERE
    CONCAT(firstname. ' ', lastname) = ?

Using your existing code in PHP (for copy+paste):

$sql = "SELECT * FROM tbl_name WHERE CONCAT(firstname, ' ', lastname) = '" . $user . "'";

* Also worth noting: since you're using MySQL you can legally-use single-quotes and/or double-quotes for strings in your queries (T-SQL is bound to single quotes for strings). Because of this, if you're wrapping your whole query with double-quotes in PHP you can use single-quotes inside your SQL-query instead of having to escape your double-quotes. This is more of a programmer's-preference tip, but one that may save you a quote-escaping headache one day =P

Upvotes: 1

Related Questions