Performing MySQLi searches that contain URL encoded strings - php

I am having trouble retrieving data from a database, when the field contains a URL encoded string.
What I mean is, my MySQLi database contains a field called "artist_name", where some of the values contain URL encoded strings, such as:
"Sonny+O'Brien"
"Lil'+Joe"
"Batman+&+Robin"
etc.
When I search on these fields in PhpMyAdmin, it finds them straight away, using a select statement:
SELECT * FROM `artists` WHERE `artist_name` LIKE 'Sonny+O'Brien';
However, when I try the same thing programmatically, from within my PHP script, it returns no results:
$artist_name = "Sonny+O'Brien";
$sql = "SELECT * FROM artists WHERE artist_name LIKE '".$artist_name."'";
if ( $result = $mysqli->query( $sql ) ) {
$obj = $result->fetch_object();
}
No results.
I have tried using an addslashes() on the artist's name, and I have double-checked all the value's and I am providing them exactly as they appear in the database.
Any ideas why the URL escaped strings are not recognised in my SELECT queries?
edit:
(screenshot from PhpMyAdmin, showing that my data is stored as described, and that my SELECT query works from within PhpMyAdmin, just not from my PHP script).

Related

Use pg_query_params array placeholders for searching multiple columns

I pass two different values into the file, one which the user entered and the other which is selected from a predefined set of values in a drop down menu, which is the one i'm having trouble with.
When using a single placeholder for the query it works,for example:
$result = pg_query_params($con, "SELECT * FROM chemsub WHERE name like $1", array("%".$_REQUEST['term']."%"));
I want to alter the query so the user can change which column they are searching i can't seem to get it to work, here is what i have
$result = pg_query_params($con, "SELECT * FROM chemsub WHERE $1 like $2", array($_REQUEST['dropdown'],"%".$_REQUEST['term']."%"));
I know the correct value is being passed into the file with the correct spelling matching a column name in the database but for some reason it returns no rows.
Any help would be much appreciated.
You can't have params in place of identifiers. If you want to have a dynamic column being queried again you can either prepare the query text in php or have the sql look like ($1 = 'foo' AND foo LIKE $2) OR ($1 = 'bar' ANd bar LIKE $2.`

Selecting a string with an Ampersand in it with php on a postgres database

I'm working on a group project from school which requires selecting from a Postgres database with php.
I tested my queries on the psql dbms before trying them in the php interface. This is my test query:
SELECT m.movieid, m.tomatourl FROM movies m WHERE title = 'Beowulf & Grendel';
The query does return the information from the database I need, however when using this in php it returns nothing.
pg_last_error() says nothing.
In what way can I ensure that I can select titles with ampersands(&) in them?
I've tried seperating the string and putting them back together with sql code:
SELECT m.movieid, m.tomatourl FROM movies m WHERE title = 'Beowulf '||chr(38)||' Grendel'
I've tried escaping the string
This is an example of some of my php code:
$query = 'SELECT m.movieid, m.tomatourl FROM movies m WHERE title = $1';
pg_prepare($conn, "getmovie", $query) or die(pg_last_error());
$result = pg_execute($conn, "getmovie", $i) or die("Query failed: ". pg_last_error());
$movie = pg_fetch_array($result, NULL, PGSQL_BOTH);
This will work as long as the string in the $i array does not have an ampersand in it.
I would just change the database to not have an ampersand, but I don't really have control over it.
Is there some way to do a select statement like this using the php postgres functions?
The problem seems to have been caused by the the quotes that are around the string that passed in to the sql, by passing the string directly through the prepared statement it is like this "Beowulf & Grendel"
when it has to be passed to the database like this 'Beowulf & Grendel'
It also seems that even though it wasn't showing in var_dump() directly in the string printout it
was actually sending it as this SELECT m.movieid, m.tomatourl FROM movies m WHERE title = 'Beowulf & Grendel'; The the only thing that gives it away it the character count in the var_dump and not the printout of the string. The fix for this was to do html_entity_decode() on the title passed in.
Special thanks to DarkBee and Daniel Verite for helping solve this issue.

Query with quotes not working

I am sending a Query string like:-
String query = "select * from table where id = 12345 or id like '___1435'";
in php code:-
$phone = $_REQUEST['data1'];
$result = mysql_query($phone);
return $result;
through android but it is not working.
But a query like:-
String query = "select * from table where id = 12345 or id = 21435";
is working.
I also tried:-
$phone = mysql_real_escape_string($_REQUEST['data1']);
$result = mysql_query($phone);
return $result;
What could be the problem.
Most probably it is related to the quotes I am using in String.
How can I overcome this ?
Thank You!
A LIKE query needs percentage signs to signify a wild card, which I assume you are trying:
id like '%___1435%'
If you don't want this wildcard behaviour then you could just remove the like
id = '___1435'
I think the problem is that you're attempting to perform a string comparison on an integer field. Try casting your ID field as a CHAR first, like this:
select * from table where id = 12345 or CAST(id as CHAR) like '___1435'
Edit: It's going to be a guessing game unless you can a) post some error logs or b) post your MySQL query log (to see the actual query executing), which you can enable by turning on the General Query Log for your installation. Since it looks like you're accepting your query string via POST, if the string has been encoded in any way (ie url encoding), it'll affect your query if not properly decoded first.
A better and more secure approach would be to create a specific web service that accepts the ID to query, which you can pass into a prepared statement server side. It's better practice anyway so your system isn't vulnerable to wide open queries from a client.

PHP & MySQL SELECT Substring

$content is a variable with a 'detailed description'.
product_id is column which might contain a substring of the detailed description ($content) in a MySQL table called products
I am trying to create a select statement that would find a record if the product_id is CONTAINED in the $content variable. Then I want to update another table called receive_sms with the url field from the SELECT staement
Researching on the website I have come up with the following.... But it doesn't work
$mysqlic = mysqli_connect("testsms.cloudaccess.net", "username", "password", "testsms2");
$prod_res=mysqli_query($mysqlic,"SELECT url from products
WHERE %product_id% LIKE %$content%");
mysqli_query($mysqlic,"INSERT INTO recieve_sms (comments) VALUES ('$prod_res')");
Any Ideas??
It should be:
$prod_res = mysqli_query($mysqlic, "SELECT url from products
WHERE '$content' LIKE CONCAT('%', product_id, '%')");
or:
$prod_res = mysqli_query($mysqlic, "SELECT url from products
WHERE LOCATE(product_id, '$content') != 0");
You need to put $content in quotes.
Actually, it would be better if you used a prepared query, then '$content' would become a placeholder ?.
After you query, you need to call mysqli_fetch_assoc() to get the column value:
$row = mysqli_fetch_assoc($prod_res);
$url = $row['url'];
Well, first of all, I don't understand why you're using wildcards on you field name. You want to check if a value is contained within the value of that field, consider changing this:
... WHERE %product_id% LIKE %$content%);
to
... WHERE product_id LIKE '%$content%');
Also, please, use prepared statements to avoid SQL injection. You're using MySQLi, which supports them.
EDIT
Also, the return of a mysqli_query is a MySQLi Resource. You'll have to fetch the results from the resource to gain access to the value you're looking for.

T_STRING error - Trying to use PHP array in SQL where statement

I feel like I'm making a rookie error here somewhere but can't figure out what's going wrong. I am using PHP and mySQL. I have an array $users that stores a current user's information. The array is storing the customer id (cid, its an integer). So I'm trying to pull information that is only tagged to a specific customer. My code is:
try
{
$sql = 'SELECT id, title, image_url FROM shelf WHERE cid = $user['cid']';
$result = $pdo->query($sql);
}
I feel like I have similar code in other parts of my program that are working so this seems like I may be doing something wrong in terms of syntax. If I replace $user['cid'] in the request with a hard-coded number like 22, the statement works fine. However, I need to pull the integer from $user. I'm getting a T_STRING error on the SELECT statement line. I have also tried to add an additional set of single quotes around $user['cid'] but that's not working either (i.e. $user['cid'])
Thanks for your help.
Twine
You're using PDO, so you should be using place-holders, too:
$stmt = $pdo->prepare('SELECT id, title, image_url FROM shelf WHERE cid=:cid');
$stmt->bindParam(':cid', $user['cid']);
$stmt->execute();
This ensures your data is escaped correctly and handles conversion to the appropriate database format where required.
Yup, rookie error. Change to double quotes and add { } around value like:
$sql = "SELECT id, title, image_url FROM shelf WHERE cid = {$user['cid']}";
$sql = 'SELECT id, title, image_url FROM shelf WHERE cid = '.intval($user['cid']);

Categories