Given the following code:
$sql = "SELECT * FROM items WHERE name LIKE '%?%'";
$key = 'orange';
$result = \DB::select(\DB::raw($sql), [$key]);
the result is always no records!
while by changing LIKE to =, it works fine:
$sql = "SELECT * FROM items WHERE name = ?";
I don't know why this is happening but I have to use RAW in this script. Can anybody figure out where is the problem?
You're failing to understand how bindings work... binding not only handles quotes and other special characters within the value, but also handles the quoting
$sql = "SELECT * FROM items WHERE name LIKE ?";
$key = '%orange%';
$result = \DB::select(\DB::raw($sql), [$key]);
and note the % around the $key value before you bind it
Related
Here's The code we have tried so far.
What actually we have to do is user will input data in his selected textboxes. we want php query to combine the search result and provide output.
$query=array();
$query[] = empty($_POST['keyword_s_dec']) ? : 'cand_desc='.$_POST['keyword_s_dec'];
$query[] = empty($_POST['keyword_s_location']) ? : 'cand_location='.$_POST['keyword_s_location'];
$results = implode('AND', $query);
$sql = "SELECT * FROM candidate where '".$results."'";
$result = mysql_query($sql) or die(mysql_error());
Where keyword_s_dec & keyword_s_location are our texfield ID;
cand_desc & cand_location are database columns.
Also we are trying for SQL Injection how can we achieve this?
I did some adjustments to your code:
$query = array();
if (!empty($_POST['keyword_s_dec'])) $query[] = "cand_desc = '".$_POST['keyword_s_dec']."'";
if (!empty($_POST['keyword_s_location'])) $query[] = "cand_location = '".$_POST['keyword_s_location']."'";
$condition = implode(' AND ', $query);
$sql = "SELECT * FROM candidate WHERE $condition";
$result = mysql_query($sql) or die(mysql_error());
This builds a valid query:
SELECT * FROM candidate WHERE cand_desc = 'test1' AND cand_location = 'test2'
Your main issue was that you weren't inserting spaces around the AND string and single quotes for the values in the WHERE clause, but I also removed the conditional ?: operator since it made the code less readable.
Note that I only fixed the code that you wrote. It won't work if none of the POST variables are set (since then the SQL string will have a WHERE clause without any content) and you should definitely use mysql_real_escape_string() when reading the POST variables to prevent SQL injection.
I have a php code with a query:
$query = "SELECT * FROM TDdb WHERE status = $status AND occupation =$occupation";
I am sending the values status and occupation with a client application to this php code.
This works when I send both status and occupation. But I want it to return rows if I just send status but not occupation also ( I mean no matter what the occupation is).
does anyone have any suggestions?
I would appreciate any help.
PS: I want to do it without if statement and just but changing the query
Personally I would create a base query and append conditions wherever you have them, like so:
$sql = 'SELECT * FROM TDdb';
$conditions = array();
$args = array();
if ($action) {
$conditions[] = 'status = :status';
$args[':status'] = $status;
}
if ($occupation) {
$conditions[] = 'occupation = :occupation';
$args[':occupation'] = $occupation;
}
if ($conditions) {
$sql .= ' WHERE ' . join(' AND ', $conditions);
}
$stmt = $db->prepare($sql);
$stmt->execute($args);
Looks like you've got a few good options for how to do it in SQL, or how to make the SQL string variable in PHP.
One reason to consider using an 'if' in the PHP code for the database access performance.
When you introduce an 'or' condition like that in SQL, you're not going to get index access. It is much harder for the database to determine what path it should take than for the PHP code because the SQL engine optimizes the query without knowing what the variable will resolve to at execution.
You already know in the PHP which version of the query you really want. This will perform better if you make that choice there.
This will work if you pass an occupation or a NULL value.
SELECT *
FROM TDdb
WHERE status = $status
AND ($occupation IS NULL OR occupation = $occupation)
"SELECT * FROM TDdb WHERE status = '$status' AND (occupation = '$occupation' OR occupation IS NULL)";
Apart from the solution provided by #Tom and #Damien Legros, you may create two query strings one with occupation and one without occupation. Something like:
$query = "SELECT * FROM TDdb WHERE status = $status";
if ($occupation != "") {
/*When you have value for occupation*/
$query .= " AND occupation =$occupation";
}
So in this case, data will be returned if you have only the status field. Secondly, please check if the status and occupation fields in table are varchar then you have to enclose them in single quotes (').
Thanks everyone for help. specially jack.
finally i created my query like this:
$query = 'SELECT * FROM TDdb';
if ($status) {
$query = $query." WHERE status = '".$status."'";
}
if ($occupation) {
$query = $query." AND occupation = '".$occupation."'";
}
$results = mysql_query("select * from doctorlist where assignednumber = '1231231234' ");
I need to change the number 1231231234 to a variable. If I change it to the code below it does not work. I have displayed the variable on the page so I know it is set.
$results = mysql_query("select * from doctorlist where assignednumber = '$phoneNumber' ");
Could someone please help. I know it is a small issue, but have been unable to fix it.
Perhaps split it like this
$sql_query = "select * from doctorlist where assignednumber='$phoneNumber'";
$results = mysql_query($sql_query);
or
$sql_query = "select * from doctorlist where assignednumber='".$phoneNumber."' ";
$results = mysql_query($sql_query);
First check your variable type with var_dump($phoneNumber) than do the following:
$results = mysql_query("select * from doctorlist where assignednumber = '".$phoneNumber."' ");
to improve readability and last if you expect an Integer cast your variable like:
(int)$phoneNumber
or if string do
mysql_real_escape_string($phoneNumber)
Try using the variable inside the query like this:
'{$phoneNumber}'
I'm having slight difficulties (syntax presumably) formulating a query for a search I'm writing in php.
So far I have this:
$query = ("SELECT * FROM $table WHERE $field LIKE "$trimmed);
trimmed is defined as
$trimmed = trim($var);
What I'm trying to accomplish is, use that query to search for a certain row in my mysql database. I've confirmed that it does indeed connect to the dbase and it does grab data from the table. I'm 99% new to php and mysql, I've just started working on this. Any help would be greatly appreciated.
EDIT: Oh I use the query here:
$result = mysql_query($query); I'm sure the issue isn't here, but in $query
Change
$query = ("SELECT * FROM $table WHERE $field LIKE "$trimmed);
to
$query = "SELECT * FROM $table WHERE $field LIKE '$trimmed'";
It's always a good idea to escape any special characters, such as backslash, in the input. With mysql, you can use mysql_escape_string:
$trimmed = mysql_escape_string($trimmed);
$query = "SELECT * FROM $table WHERE $field LIKE '$trimmed'";
Equivalent commands exist in mysqli, PDO, and all PHP frameworks.
Check out the PHP manul, example:
$query= mysql_query("SELECT data FROM mydb;");
$myarray= array();
while ($row= mysql_fetch_array($query)) {
$myarray[] = $row['data'];
}
EDIT
This is your code? if so, you have a syntax error:
$query = ("SELECT * FROM $table WHERE $field LIKE "$trimmed);
should be:
$query = ("SELECT * FROM $table WHERE $field LIKE '$trimmed'");
i have a problem with php in the following:
$sql = 'SELECT name FROM chiled WHERE `im` LIKE $id ';
$query = mysql_query( $sql );
$a=mysql_fetch_row($query);
echo $a[0];
there is error in mysql_fetch_row($query);
but if i do the following :
$sql = 'SELECT name FROM chiled WHERE `im` LIKE 1111 ';
$query = mysql_query( $sql );
$a=mysql_fetch_row($query);
echo $a[0];
it is working and prints the name
can you please tell me what is wrong?
Single quotes in PHP doesn't evaluate embedded variables - you need to use double quotes to do that. (See the "Single quoted" section of the PHP Strings manual page for more info..)
i.e.: $sql = "SELECT name FROM chiled WHERE 'im' LIKE $id ";
Or better still...
$sql = 'SELECT name FROM chiled WHERE im="' . mysql_real_escape_string($id) . '"';
(As you're not using the % in your like, you're presumably not attempting to do any form of pattern matching.)
Additionally, I'd recommend a read of the existing Best way to stop SQL Injection in PHP question/answers.
Are you sure you want to be using LIKE? It looks more to me like you want to see if im = $id. Also, make sure you're escaping your variables before using them in the query.
Edit
If you DO want to us LIKE, you probably want something like this:
$sql = "SELECT name FROM chiled WHERE `im` LIKE '%$id%' ";
which will find anywhere that the string $id is found in the im column.
You need to quote the variable after LIKE, like this:
$sql = "SELECT name FROM chiled WHERE im LIKE '$id'";
$query = mysql_query($sql);
$a = mysql_fetch_row($query);
echo $a[0];
// ....
Beside, you are using single quotes, Therefore, $id is not replaced for its value. Your query look like this:
SELECT name FROM chiled WHERE im LIKE $id;
$sql = "SELECT name FROM chiled WHERE `im` LIKE '$id' ";
change to double quotes - http://php.net/manual/en/language.types.string.php