How do I check a column that contains a string? - php

currently I've been using this:
SELECT * FROM `meow` WHERE profile LIKE '%$username%'
But the problem I'm facing is if someone puts the letters 'a' it will pull everything that contains a and that's a bit of a security risk on my end, How do i search just 1 column to see if it matches $username exactly? not the whole table?

For exact string matching you should the = operator instead of the like operator:
SELECT * FROM `meow` WHERE profile = '$username'

Stop using string concatenation to build your query. It's evil. Instead use mysqli or pdo and use prepared statements.
$pdo = new PDO('mysql:host=localhost;dbname=yourdb', 'your_username', 'your_password');
$stmt = $pdo->prepare("SELECT * FROM `meow` WHERE profile = ?");
$stmt->execute(array($username));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Also, use equality, instead of like, if you wish to check for exact matches.

Instead of using like use equal to
try this :
SELECT * FROM meow WHERE profile = '$username'

Try with -
"SELECT * FROM `meow` WHERE profile LIKE '$username'"
for exact match.

Related

SQL LIKE literally not showing any results (at all)

I tried to make a search system which uses the LIKE operator to search results based on what the user typed. I'm using it with strings. The problem is that it doesn't show any result.
I hope this also helps people with the same confusion as me...
Code:
"SELECT * FROM table WHERE name LIKE ' . $input . ';";
input is a PHP variable from what the user typed.
EDIT: Don't worry about SQL injection, it's all offline.
for the proper use of like you should use wildchar eg :
SELECT * FROM table WHERE name LIKE concat('%', ? ,'%') ;
and you should not use var inside SQL code .. you are at risk for sqlinjectiomn
for avoid this you should take a look at you db driver for prepared statement and binding param
eg for PDO
$st = $conn->prepare("SELECT * FROM table WHERE name LIKE concat('%', ? ,'%')");
$st->bindParam(1, $input, PDO::PARAM_STR, 255);
$st->execute();
Try This
$string = "input";
$sql = "select * from table where name like '%$string%'"
Create a variable and store value what you want to search
$where = "AND name like '%$string%'";
and put it after table name
$sql = "select * from table_name $where";

checking for the existence of a word a mysql row(php)

i have a mysql table users like this:
id username following
15 one ,13,14,16,17,
14 two ,76,43,13,
13 three null
now three has 0 following and 2 followers.
and i want a query to check for all users who have ,13, in the following row
Something like this:
$query = mysql_query('SELECT * FROM users WHERE following has ",13,"');
but works.
I can select all the following of each user and do this:
if (strpos($result_from_query,',13,') !== false) {
echo $fetch['username'];
}
Have you tried using LIKE?
$query = mysql_query('SELECT * FROM users WHERE following LIKE "%,13,%"');
The % characters before and after the ,13, string act as a wildcard allowing any characters to be there, so will find ,13, in any position in the string.
Also, as an aside, #Jay Blanchard has suggested using the IN operator (in his answer)
I would use IN for greater flexibility if the value in the following column is an array.
SELECT *
FROM `users`
WHERE `following` IN(13)
Assuming that the numbers always have starting and trailing commas you can use:
$query = mysql_query('SELECT * FROM users WHERE following LIKE "%,13,%"');
Please read up on LIKE statements for more info

When to use mysql_real_escape_string()

When is the correct time to use mysql_real_escape_string?
Should I be using it when I use isset(mysql_escape_string($_GET['param'])),
Should I be using it when I use $foo = mysql_real_escape_string($_GET['bar']);
Thanks
You need to call this function when building SQL queries with string literals.
You should not call it anywhere else.
The point of calling this function is to prevent you from executing SQL like SELECT * FROM Students WHERE Name = 'Robert'); DROP TABLE Students;--'.
mysql_real_escape_string will escape the ' character so that the evil string is treated entirely as a string.
You should use it whenever you don't trust the data you are inserting in a mysql query to prevent sql injections. For example all user forms data.
In your first example: no.
Second example: yes, if you are going to use the $foo variable in a query.
You should use it whenever you are inserting data into a database query (POST/GET data), but not if you just need to check the data.
You use mysql_real_escape_string whenever you have input from a user that you want to use in a query.
Here's how to use it:
$user = mysql_real_escape_string('$_GET['user']);
$password = MD5($user.$_GET['password']);
$query = "SELECT * FROM users WHERE user = '$user' AND password = '$password' ";
//the quotes are vital !! ^ ^ or you will not be safe!
Here's example code that doesn't work:
Broken code
$user = mysql_real_escape_string('$_GET['user']);
$password = MD5($user.$_GET['password']);
$query = "SELECT * FROM users WHERE user = $user AND password = '$password' ";
In the example I can login into your system by entering any password whatsoever and
user or (1=1) --. This will make the query to read:
SELECT * FROM users WHERE user = user or (1=1) -- AND password = '$password
And will approve all logins because the password never gets checked.
When using mysql_query, you can only ever execute one SQL-statement at a time, so:
$query = "SELECT * FROM a; DELETE FROM a WHERE (1=1)"
mysql_query($query);
Will result in an error, because cannot be a part after the ;.
This code however will work:
Danger
$query = "SELECT * FROM a; DELETE FROM a WHERE (1=1)"
mysqli_query($query);
Because the improved mysqli_query does allow two or more statements to be executed in one go.

MySQL Query Selecting records from a database where a value equals one of two different things

I have to get records from my MySQL DB where:
sentto = "$username"
OR
sentto = "everyone"
How would I put this in a MySQL query? I tried a few things, but they don't seem to be working:
mysql_query("SELECT *
FROM pmessages
WHERE status='unread'
AND sentto='$username' || sentto='everyone'");
mysql_query("SELECT *
FROM pmessages
WHERE status='unread'
AND sentto='$username'
AND sentto='everyone'");
I seem to be stumped, if anyone knows how to do this the right way please let me know. This is a new scenario for me. Thank you!
SELECT *
FROM pmmessages
WHERE sentto = '$username'
OR sentto = 'everyone'
Edit Chris, based on your new query of:
SELECT *
FROM pmessages
WHERE status='unread'
AND sentto='$username'
OR sentto='everyone'
You need to modify it so that your AND stands alone (it is conflicting with your OR).
Rewrite it to this
SELECT *
FROM pmessages
WHERE status='unread'
AND
(sentto='$username'
OR sentto='everyone' )
Taking the detail from one of your comments into account - use the " OR " keyword and parentheses to make sure that the right conditions are combined.
SELECT * FROM pmessages WHERE
status = 'unread'
AND
(sentto = ? OR sentto = 'everyone')
Your problem was never with the OR, though, it was actually the AND precedence and lack of parentheses. The very significant detail that you completely omitted from your question was the additional test for "status = unread".
Note the use of ? above - you should really, really use prepared statements whenever combining MySQL and PHP, i.e.:
$sql = "..." # as above
$sth = $db->prepare($sql);
$res = $sth->execute($username);
while ($row = $sth->fetchrow()) {
...
}
(or the mysqli equivalent)
As it's the same column you're testing, I would use the IN keyword:
SELECT *
FROM pmessages
WHERE status='unread'
AND sentto IN ('everyone', '$username');
The word OR is what you're looking for:
mysql_query("SELECT * FROM pmessages WHERE sentto='$username' OR sentto='everyone'");
is everyone an actual value or do you want to return all results?
if you want to return all results set up something like this
if (#sentto is null)
begin
set #sendto='%'
end
mysql_query("SELECT * FROM pmessages WHERE sentto='$username'")

Coding of parameter-value for SELECT in PHP-MySQL

Alt A below is a statement from a php-mysql tutorial. It works as it should.
I found the id-value rather obfuscated and tested alt B. This also worked!
What is the point with the id-value of alt A?
MySQL 5.0.51, PHP 5.2.6
// Alt A :
$sql = "SELECT * FROM example WHERE id = '".$q."'";
// Alt B :
$sql = "SELECT * FROM example WHERE id = $q";
This are just two different approaches to building a string from static and variable data.
Alternative A uses concatenation, or the joining of string and variable tokens using the concatenation operator.
Alternative B uses variable expansion, wherein the variables inside a double-quote-delimited string are expanded to their values at evaluation time.
Neither is necessarily better or preferred, but if you have to have single-quote-delimited strings, for example, then you would need to use alternative A.
Of course, neither of these is preferable to building SQL queries with bound parameters, as not doing so leaves you vulnerable to SQL injection attacks.
Theres two reasons to use the example in 'Alt A'. First is if the string is enclosed in single quotes '', the variable's name will be used in the string instead of it's value.
$id = 7;
'SELECT * FROM table WHERE id = $id' //works out to: WHERE id = $id
"SELECT * FROM table WHERE id = $id" //works out to: WHERE id = 7
Secondly, it's useful to combine strings with the results of a function call.
"SELECT * FROM table WHERE id = '".getPrimaryId()."'"
Outside of what has already been said I've found it best practice, if I'm writing a query, to write it as so:
$sql = "SELECT * FROM table WHERE uid=" . $uid . " LIMIT 1";
The reason for writing SQL like this is that 1. MySQL query doesn't have to parse the PHP variables in the Query and 2 you now easily read and manage the query.
When PHP communicates with MySQL, it is actually (in essence) two languages communicating with each other. This means that a string will be processed by the first language before being sent to the other. It also means that it is important to think in terms of the receiving language
In this case:
$q = 'some_name';<br/>
$query = "SELECT * FROM exempel WHERE id = $q";<br/>
you are telling MySQL to
"SELECT * FROM example1 WHERE id = some_name.
In this case:
$q = 'some_name';<br/>
$query = "SELECT * FROM exempel WHERE id = '$q'";<br/>
and this case:
$q = 'some_name';<br/>
$query = "SELECT * FROM exempel WHERE id = '".$q."'";<br/>
you are telling MySQL to
"SELECT * FROM example1 WHERE id = 'some_name'.
The first example should cause an error as some_name is not a valid part of a MySQL query (in that context). On the other hand, the next two will work fine, because MySQL will look for the String "some_name".
You can also do this:
$sql="SELECT * FROM exempel WHERE id = {$q}";
which is useful for setting off things like:
$sql="SELECT * FROM exempel WHERE id = {$row[id]}";
in 'alt B', $q must be an int or float or other numeric
in 'alt A', $q can be anything a string, int, etc.
The single quote makes that possible. It's just hard to see sometimes if you are looking at it for the first time.

Categories