简体   繁体   中英

php select statement doesn't give answer

I used php code from tutorial and it worked fine. But when I am rewriting it to me it gives me null. This code gives me what I want I mean it gives data in JSON format:

$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
    $output[]=$e;
print(json_encode($output));

But this code even it looks identically doesn't work it gives null:

$q=mysql_query("SELECT username, firstname, lastname, email, phone1, skype, city, description 
FROM mdl_user WHERE username LIKE'".$_REQUEST['usern']."'");
while($e=mysql_fetch_assoc($q))
    $output[]=$e;
print(json_encode($output));

If I don't use $_REQUEST['usern'] and am getting data in JSON. But I need to use request to search specific data. So where could be the problem. Because I trustfully don't understand. It looks the same to me.

To make a pattern with LIKE use a % . Put it around or at any end, beginning or end.

$username = mysql_real_escape_string($_REQUEST['usern']);

$q=mysql_query("SELECT username, firstname, lastname, email, phone1, skype, city, description 
FROM mdl_user WHERE username LIKE '$username%'");
                                 ^
                                 |
 // You also missed this space --+

Note your query is wide open to SQL injection. Just think if someone inserts year as '; drop table people; -- '; drop table people; -- '; drop table people; -- . Use mysql_real_escape_string to sanitize those field.

在此处输入图像描述

And it's better to use explicitly $_POST or $_GET,ths makes sure your data is coming from proper source.

With LIKE you can use the following two wildcard characters in the pattern.

%   Matches any number of characters, even zero characters
_   Matches exactly one character

I assume that you are getting no result because your username is not the exact same as $_REQUEST['usern'], and that's why you're using LIKE in the first place. You should therefore place wildcard characters to tell MySQL to look for any characters (%) before or after your string, for example:

LIKE '%".$_REQUEST['usern']."%'

Keep in mind that this is inefficient and you should try to use only one % after the string (if this will work for you), or better yet, find another way to search the table.

Edit: Also as a user in the comments noted and I failed to mention, this particular code is vulnerable to SQL injections. You should sanitize the variable $_REQUEST['usern'] before passing it onto the query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM