MySQL Query with variable wildcards - php

If I execute my PHP code:
$serName = $_GET['username'];
// Code for sanitation here
// [...]
$sql = "SELECT NAME FROM PLAYERS WHERE NAME LIKE '%$serName%'";
I get division error, how do I use a variable in a query with wildcards on both sides?

right query
SELECT NAME FROM PLAYERS WHERE NAME LIKE '%{$serName}%'
And you should use prepared statements

$sql = "SELECT NAME FROM PLAYERS WHERE NAME LIKE '%" .$serName. "%'";

Related

How to fetch the record when Query string with the single quotes string in Php

I am fetching data from the MySQL Database and database has a table name
wp_evr_event. I am fetching records using event_name from wp_evr_event.
wp_evr_event table has a fiels name event_name that use name of event.
now event name is Women\'s Reading Group into database.
when I used the Query
$sql = "SELECT * FROM `wp_evr_event` WHERE `event_name` LIKE '%".$_REQUEST['events_name']."%' ";
echo $sql;
Query become like
SELECT * FROM `wp_evr_event` WHERE `event_name` LIKE '%Women \'s Reading Group%'
But this is not fetching any record.
For the wordpress wpdb class you should use 2 functions. esc_like & prepare
A small example:
global $wpdb;
// First, escape the link for use in a LIKE statement.
$link = $wpdb->esc_like( $_REQUEST['events_name'] );
// Add wildcards
$link = '%' . $link . '%';
// Create a SQL statement with placeholders for the string input.
$sql = "SELECT * FROM `wp_evr_event` WHERE `event_name` LIKE '%s'";
// Prepare the SQL statement so the string input gets escaped for security.
$sql = $wpdb->prepare( $sql, $link);
If you prepare your query like this you should get the expected result.

oci_bind_by_name() returns error

I'm using PHP to query oracle DB and everything works great unless i try to use oci_bind_by_name to replace a variable
$link = oci_connect("user","password","server/service");
$sql = "SELECT name FROM customers WHERE name LIKE '%:name%'";
$query= oci_parse($link, $sql);
$name = "Bruno";
oci_bind_by_name($query, ":name", $name);
$execute = oci_execute($query);
I also tried to escape the quotes like this, but it returns the same error, i assume it's a problem with the wildcards %
$sql = "SELECT name FROM customers WHERE name LIKE \"%:name%\" ";
The error is not specific:
( ! ) Warning: oci_bind_by_name(): in D:\gdrive\www\sites\pulseiras\php\engine.php on line 30
I'd like to use bind by name to avoid sql injection, how can i make it work ?
OCI is inserting the bound variable to your query and ending up with something like this:
SELECT name FROM customers WHERE name LIKE '%'Bruno'%'
Obviously a couple of unnecessary quotes have been added. This happens because a bound variable is treated as a single item.
You need to modify the variable before you bind, so:
$sql = "SELECT name FROM customers WHERE name LIKE :name"; // chars removed.
$query= oci_parse($link, $sql);
$name = "%Bruno%"; // chars added.
oci_bind_by_name($query, ":name", $name);
As usual, the PHP manual has many useful examples.
It's amazing how the brain only seems to start working after posting the question on stackoverflow. It turns out the solution is to isolate the wildcards and concatenating with the variable:
$sql = "SELECT name FROM customers WHERE name LIKE '%' || :name || '%' ";
$name = "Bruno";
oci_bind_by_name($query, ":name", $name);
$execute = oci_execute($query);

trouble passing php variable into mysql string

I have been trying to get this for hours, and I know there are other topics similar to this but I'm still stuck... basically I'm trying to list all the customers with last names that start with the letter A:
I'm passing a variable called lname in the URL like this:
Then I grab the variable in the PHP like:
$lname = $_GET['lname'];
$lname = mysql_real_escape_string($lname);
// HERE'S THE PROBLEM AREA: then I try to put a simple query together like this:
$query = 'SELECT * FROM customers WHERE customers.lname LIKE "$lname%"';
// then I want to make sure $query and $lname have values in them, so I echo them out:
echo $query;
echo ' $lname = '.$lname;
// and the output is:
SELECT * FROM customers WHERE customers.lname LIKE "$lname%"
$lname = A
Unknown column '$lname' in 'where clause'
So you can see that in the query, after the LIKE, it should say LIKE 'A', but it is parsing to LIKE $lname. I've tried all kinds of variations such as:
$query = 'SELECT * FROM customers WHERE customers.lname LIKE ".$lname."';
$query = 'SELECT * FROM customers WHERE customers.lname LIKE {$lname}%';
etc, etc, etc
Strange, but the column lname is DEFINITELY there in the customers table, and so I'mk not sure why it's reporting that error of 'Unknown column '$lname' in 'where clause''
And for the record, when I manually just change the query to include the value I want, it outputs the list of customer names perfectly:
$query = 'SELECT * FROM customers WHERE customers.lname LIKE "A%"';
... so the query works, but I can't get the $lname to be interpolated.
THANK YOU for any help. How can I get that variable $lname to pass the VALUE that's inside of $lname in my mysql query?
$query = "SELECT * FROM customers WHERE customers.lname LIKE '$lname%'";
Interchange your single quotes and double quotes in the above line.
You should really think about using parameterized queries. For instance,
$sql = "SELECT * FROM customers WHERE customers.lname LIKE ?";
$stm = $pdo->prepare($sql);
$stm->execute(array($lname));
This would help with many problems you are likely experiencing, and is much more secure.

PHP Query failing, show error?

I have a query on my page that uses a GET variable to pull data from my table...
If I echo my GET var the data is there so im doing something wrong with my query, instead of or die can I show an error in the browser?
// Get USER ID of person
$userID = $_GET['userID'];
// Get persons
$sql = 'SELECT * FROM persons WHERE id = $userID';
$q = $conn->query($sql) or die('failed!');
$sql = "SELECT * FROM persons WHERE id = $userID";
You must use double quotes to use variables inside the query string.
You can also do this:
$sql = "SELECT * FROM persons WHERE id = ".$userID;
What you should do is this (to protect yourself from sql injection):
$safeuid = $conn->prepare($userID);
$sql = "SELECT * FROM persons WHERE id = ".$safeuid;
You can always debug using this at the top of your php page:
ini_set('display_errors',1);
error_reporting(E_ALL);
Have you tried $q = $conn->query($sql) or die($conn->error()); ?
Yes you can, but you should only do it for debugging. Crackers can gain a lot of insight by purposefully feeding bad input and reading the error.
I'm assuming you're using MySQLi; the command is $conn->error(). So your line would be:
$q = $conn->query($sql) or die($conn->error());
Also, what you're doing wrong is you're using single quotes to define $sql. You need to use double quotes to write $userID into the string. So what you want is:
$sql = "SELECT * FROM persons WHERE id = $userID";
or
$sql = 'SELECT * FROM persons WHERE id = ' . $userID;
You need to use double quotes to evaluate variables within the string. That is,
$sql = 'SELECT * FROM persons WHERE id = $userID';
should be
$sql = "SELECT * FROM persons WHERE id = $userID";
Rather than removing the die you should make sure the query is always valid. In other words: validate the userID parameter. $_GET can contain anything the user wants to provide - it could be an array, it could be a string, it could be a string with a malicious payload that can drop your tables. So check it is an integer. If not, return a relevant message to the user.
Not a php expert but you might try:
// Get USER ID of person
$userID = $_GET['userID'];
// Get persons
$sql = 'SELECT * FROM persons WHERE id = $userID';
$q = $conn->query($sql) or die('failed!' . mysql_error());
The error should append to the end of your die message.

MySQL Select statement

I have 2 values that I'm suppling my script - I want to search for any one of those datas. How do I write my query like this:
SELECT * FROM table WHERE id = '".$id."' or "name='".$name."';
my problem is escaping the quotes in the query.
Any help will be appreciated.
There are a few ways to do it, a lot of them frowned on but generally I would stick to using MySQLi and using the
mysqli_real_escape_string($id)
function or in OOP
$mysqli = new mysqli('host', 'user', 'pass', 'database');
$id = $mysqli -> real_escape_string($id);
$name = $mysqli -> real_escape_string($name);
$results = $mysqli -> query("SELECT * FROM table WHERE id = '{$id}' or "name='{$name}'");
You may use curly brackets to avoid confusion with escaping characters as follows:
$query = "SELECT * FROM table WHERE id = '{$id}' or name = '{$name}' ";
You may also consider using wildcards such as %$letter% to search for word anywhere in the name field as:
$query = "SELECT * FROM table WHERE id = '{$id}' or name LIKE '%{$name}%' ";
SUGGESTTION:
You should always use id fields as integer for better performance.
Use this fancy function, mayhaps? The examples have what you're looking for.
You've got an extra quote; if you want to stick with your original code (not recommended), try something like this:
$query = "SELECT * FROM table WHERE id = '".$id."' or name='".$name."'";
But really you should be using parameterised queries so that you avoid possible SQL injection security issues!
Write it as:
$name = mysql_real_escape_string($name);
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM table WHERE id = '$id' or name= '$name' ";
Because you started with double quotes the single quotes are part of the query and the $vars are expanded.

Categories