1,105,556 Community Members

use of like in mysql and php

Member Avatar
daniel36
Junior Poster
188 posts since Nov 2011
Reputation Points: -7 [?]
Q&As Helped to Solve: 3 [?]
Skill Endorsements: 0 [?]
 
0
 

I am first time using like in mysql .but it is giving error.my query with like is

$user_query="SELECT * FROM rt_user WHERE rt_user_username LIKE %".$_GET['term']."% OR rt_user_name LIKE %".$_GET['term']."% OR rt_user_description LIKE %".$_GET['term']."% LIMIT 10";

it is giving syntax error.

Member Avatar
diafol
Where are my eyes?
12,991 posts since Oct 2006
Reputation Points: 1,821 [?]
Q&As Helped to Solve: 1,849 [?]
Skill Endorsements: 92 [?]
Moderator
Featured
Sponsor
 
1
 

Do not insert $_GET or $_POST vars directly into SQL -you need to sanitise.

$term = mysql_real_escape_string($_GET['term']);

$user_query="SELECT * FROM rt_user WHERE rt_user_username LIKE '%$term%' OR rt_user_name LIKE '%$term%' OR rt_user_description LIKE '%$term%' LIMIT 10";
Member Avatar
dcdruck
Junior Poster in Training
92 posts since Jul 2009
Reputation Points: 11 [?]
Q&As Helped to Solve: 20 [?]
Skill Endorsements: 0 [?]
 
0
 

Try wrapping the LIKE arguments in single quotes:

$user_query="SELECT * FROM rt_user WHERE rt_user_username LIKE '%".$_GET['term']."%' OR rt_user_name LIKE '%".$_GET['term']."%' OR rt_user_description LIKE '%".$_GET['term']."%' LIMIT 10";

Notice the single quotes around the LIKE strings?

You should definitely take diafol's advice and sanitize the input instead of just directly injecting the $_GET values into the query.

Also, I cannot be sure without seeing your database structure, but it looks like where you say rt_user_username, you might really mean to say rt_user.username, or even more simply, just username. What you have (and maybe this is what you want, like I said, I cannot be sure without seeing the schema) is looking for a column named rt_user_username in the rt_user table. What I wrote, rt_user.username, means a column named username in the table named rt_user. Just thought I'd mention that in case it turns out to be another issue.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article