Syntax Help for Query - php

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'";

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

i think it is this what you are looking for??
$sql = 'SELECT * FROM '.$tbl_name .' WHERE CONCAT(firstname," ",lastname )='.$user.' ';

Related

sql returning no results

The following code is returning no results where I use the variable in the code of $dep if I manually put the value in of 1 it returns the expected result. I have tried it with no quotes single quotes and double quotes. I have looked though loads of examples and I cannot see what I am doing wrong
$dep = 1;
if (!$names) {
$sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM '.TOPIC_TABLE
. ' WHERE dept_id='$dep' ORDER BY `sort`";
$res = db_query($sql);
I'm pretty sure your error is related to wrong quotes used.
In your code, you write
$sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM '.TOPIC_TABLE
. ' WHERE dept_id='$dep' ORDER BY `sort`";
After FROM, you are using single-quotes('), but your whole query has been enclosed into double-quotes("), so that creates the issue.
It should be:
$sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM ".TOPIC_TABLE
. " WHERE dept_id='$dep' ORDER BY `sort`";
EDIT: Forgot to point out you should seriously use PDO or any other SQL Injection prevention methods. If, under any circumstance, your $dep variable could be sent via a public form, you could end up by having your DB dumped in the best case.
There's a syntax error in the second line of the query - if you want single-quotes in the query, then you need to enclose it all in double-quotes:
$sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM ' .TOPIC_TABLE
. " WHERE dept_id='$dep' ORDER BY `sort`";
By the way, building a query like this, using string concatenation, is a REALLY BAD IDEA and leaves you open to SQL injection attacks - you should use prepared statements and parameters instead.
First as Fred -ii says make sure the if statement is executing properly. Then if dept_id is an integer value then you should not need the single quotes as scaisEdge says. Otherrwise the SQL looks fine. Make sure that there are in deed records in the database for the dept_id that is being passed in.

SQL Statement returns 500 Error

I have this SQL statement:
$sql = "SELECT CONCAT_WS (" ",Firstname, Surname) AS FullName FROM Applicant WHERE AppID=10010";
This statement returns Error 500 on my page despite of that it is a completely correct statement. I run this query on Sequel Pro and it is returning exactly what I need.
I tried a simple query and its working fine:
$sql = "SELECT * FROM Cases";
I don't know why PHP is doing that. Maybe an extra pair of eyes can solve this.
wrong double quotes sequence
$sql = "SELECT CONCAT_WS (' ',Firstname, Surname) AS FullName
FROM Applicant WHERE AppID=10010";
you must a different quote char inside the query string

difference between ' single quote and ` backtick for mysqli_query

This is bizarre, I'm changing some code from mysql to mysqli functions cause of php 5.5+, in these two basic examples, mysql_query had no ' single quote nor ` backtick and worked fine.
$sql = "SELECT * FROM `".$table."`"; // requires: ` ` or fails
$result = mysqli_query($con,$sql);
$sql = "SHOW TABLES LIKE '".$table."'"; // requires: ' ' or fails
$result = mysqli_query($con,$sql);
Can someone explain why?
EDIT: I guess the essence of my question is that: Both functions worked fine without any kind of quotes with mysql_query, and both failed mysqli_query without some kind of quotes. Meaning I will have to fiddle around with half my query's when changing from mysql_ to mysqli_
In your first select statement you are trying to select a table by it's name, hence it will accept the name either with ` or without them, but now with single or double quotes. These should work :
$sql = "SELECT * FROM `table_name`";
$sql = "SELECT * FROM table_name";
In the second case you need to pass in a string to be compared by the like statement hence you need to surround it either with single ' or double " quotes:
$sql = "SHOW TABLES LIKE 'string'";
$sql = "SHOW TABLES LIKE \"string\"";
Edit:
Check out this previous answer on SO as well:
Using backticks around field names
Edit 2:
Since we (me and in comments) suggested that backticks are somehow optional, keep in mind that as a best practise use them whenever you can since although it will allow you to pass most queries without them, some queries using MySql reserved words would break when containing mysql reserved words

What's wrong in this simple PHP SQL sentence?

i want to recober all the users with "blo" in their full name, for example: "Pablo"
I pass the "blo" parameter with user PHP parameter:
$q=mysql_query("select * From user Where fullName Like '%'".$_REQUEST['user']."'%'",$link );
something is wrong in the php SQL sentence, because when i try the sentence with the argument "blo" on my SQL database, i see that the SQL sentence is correct, because it returns me correct result, this is the sentence with the argument "blo" on it: select * From user Where fullName Like "%blo%"
i'm sure that the PHP is receiven the "blo" parameter correctly, then, it have to be a sintax error of the SQL sentence on the PHP.... but i can't find it
EDIT : OK!! the last sentence is solved, but now i have this new sentence with the same problem, it have a error but i dont know where
$query = sprintf("SELECT u.*
FROM USER u
WHERE u.fullName LIKE '%%%s%%' AND email NOT IN (select pp.fk_email2 from permission pp where pp.fk_email1='".mysql_escape($_REQUEST['mymail'])."') AND email NOT LIKE '".mysql_escape($_REQUEST['mymail'])."' ",
mysql_real_escape_string($_REQUEST['user']));
SQL requires single quotes to indicate a string for comparison, and the wildcard character (%) must be included inside of those single quotes. Double quotes are used for column and table aliasing only, if at all.
$query = sprintf("SELECT u.*
FROM USER u
WHERE u.fullName LIKE '%%%s%%'",
mysql_real_escape_string($_REQUEST['user']));
$q = mysql_query($query, $link);
Secondly, you're leaving yourself open to a SQL injection attack by not sanitizing the user request variable. Always use mysql_real_escape_string when dealing with strings being submitted to a MySQL database.
You have the quotes messed up. use this:
$q=mysql_query('SELECT *
FROM user
WHERE fullName LIKE "%' . $_REQUEST['user'] . '%"',$link );
BTW, this is bad practice. You are using un-escaped input in your query and are open to SQL injection.
It looks like your quotes are off.. try something like...
$q=mysql_query("select * From user Where fullName Like '%".$_REQUEST['user']."%'",$link);
Also, you will want to make sure that the incoming param is sql-escaped to prevent sql injection. I don't know php, but it's probably something similar to...
$q=mysql_query("select * From user Where fullName Like '%".mysql_escape($_REQUEST['user'])."%'",$link);
I think it must be ... Where fullname like '%" . $_REQUEST['user']."%'"...
with the % symbol inside the simple quotes.
#AndroidUser99: Change the query to --
$q = mysql_query("select * from user Where fullName like '%" . $_REQUEST['user'] . "%'", $link);
Update
I think we may need more code since none of the answers seem to be 'working'. Is the database link even being instantiated in $link? If there are errors what are they?

php variable in regex?

I have a variable $word and I'd like to match it in my select statement
somethig like this: "select * from table where column regex '[0-9]$word'"
but this doesnt work, so how can i put a variable in a regular exprssion?
Thank you
You must only put it correctly in SQL query, for example:
mysql_query("SELECT * FROM table WHERE column REGEXP 'prefix_".$word."'");
But you need to remember that the variable data needs to be properly escaped, i think that addslashes() would be enough.
You could try using preg_quote() to escape your string:
$sql = "select * from table where column regexp '[0-9]" . preg_quote($word) . "'";
There will be some issues because MySQL (assuming this is your DB) may have a completely different idea of which characters are special than PCRE.

Categories