MySQL WHERE if one is there but other is not in database - php

I am trying to get results from MySQL. but it only works if both have a valve.
Like if both WHERE is in the database it works, but if only one is in the database and the other is not it fails, this is what I have now for the code
$check_ip = $_GET['ip'];
$check_username = $_GET['username'];
$query = "SELECT *, COUNT(ip), COUNT(username) FROM bl WHERE ip = '$check_ip' AND username = '$check_username'";
$resultID = mysql_query($query, $linkID) or die("Data not found.");
Now if both IP and username are in the database it get the results, which is great, I am also wanting result if ip is there but username is not and the other way around.
It says they both not there
What is happening is when ip and username is there is says they both there.
But if ip is not and username is, it says they both not there.
I need a reply from both, so if ip is there and username is not, I need the ip data

Why are you not using OR Operator
"SELECT *, COUNT(ip), COUNT(username) FROM bl WHERE ip = '$check_ip' OR username = '$check_username'"
use UNION
SELECT *, COUNT(ip), COUNT(username) FROM bl WHERE ip = '$check_ip'
UNION
SELECT *, COUNT(ip), COUNT(username) FROM bl WHERE username = '$check_username'"

Change the AND to OR so that MySQL counts rows if one (or both) of the two conditions is true.

As your query contains the 'AND' condition which means if both the values exists then only it will return a value. you can change the 'AND' condition to 'OR' for the desired result.

Just change the AND for an OR, please read this, it would help in the future: https://dev.mysql.com/doc/refman/5.0/en/selecting-rows.html

Related

MySQL using WHERE and OR

I am allowing people to input either their username, account number or email address before typing their password, so i need to compare their input against 3 fields in my table but i am not getting any results.
i first tried this ...
$result = mysqli_query($con,"SELECT * FROM useraccounts WHERE username='$thisuser' or accnum='$thisuser' or email='$thisuser'");
then i read on here that brackets should be placed around OR statements, so tried this ...
$result = mysqli_query($con,"SELECT * FROM useraccounts WHERE (username='$thisuser' or accnum='$thisuser' or email='$thisuser')");
but neither work, can someone help please
just for comparison, this does work when i type in the username value ...
$result = mysqli_query($con,"SELECT * FROM useraccounts WHERE username='$thisuser'");
What is the datatype of accnum? Are you sure it is varchar?
If accnum is of type numeric then try
$result = mysqli_query($con,"SELECT * FROM useraccounts WHERE (username='$thisuser' or accnum=$thisuser or email='$thisuser')");
Seems no problem. Please check '$thisuser' has value. Try printing the sql statement.
You may try running query directly on database.
I also think first check the value of $thisuser, and then try below query
$result = mysqli_query($con,"SELECT * FROM useraccounts WHERE (username='".$thisuser."' or accnum='".$thisuser."' or email='".$thisuser."')");
Rathere then using at server side if it done at client side in js file by checking it emailid or username oraccount number according to that u can pass value

PHP Forms - Which input is incorrect?

If I have a query,
SELECT (...) FROM User WHERE Username = (...) AND Password = (...);
and the user types in an invalid Username is there a way to pick up that it was specifically the Username that was incorrect?
This is so that I can give more specific error messages to the user, like "User does not exist" etc...
SELECT COUNT(*) AS `count` FROM `User` WHERE `Username` = ...;
if( $result['count'] < 1 )
{
// no user
}
// repeat for pass.
I would select the username and then a bit-field on if the password matched. So remove the password part from the WHERE clause, and move it into the SELECT clause. Then, no matching rows means invalid username, and if you have a row, you need to check that field to see if the password matches.
SELECT (...) IF(password=?, 1, 0) as success
FROM User
WHERE Username = ?
If you're adamant about doing it this way, you can do:
SELECT password FROM user WHERE username = ?
If there's no record found, the username doesn't exist. If it does, you can now compare the password.

Check two tables in one query

I have the following function:
function login_check($email, $password)
{
$email = mysql_real_escape_string($email);
$password = md5($password);
$login_query = mysql_query("SELECT COUNT(`id`) as `count`, `id` FROM `table_name` WHERE `email`='$email' AND `password`='$password'");
return (mysql_result($login_query, 0) == 1) ? mysql_result($login_query, 0, 'id') : mysql_error();
}
I want it to check if the user login is correct in two different tables not only one since I've made another table for users who have authenticated their twitter account with my site.
You'd be better off with a single table that has an "authenticated with Twitter" flag but you can check both with something like this:
select exists(
select 1 from table_name where email = '$email' and password = '$password'
union
select 1 from twitter_table where email = '$email' and password = '$password'
)
MySQL will give you a one (AKA true) if at least one of the tables has what you're looking for and a zero (AKA false) if neither has a match.
Using the select exists(select 1...) trick will also be faster than counting as the database only needs to find one match or check the indexes to know that there are no matches before it returns from the query.
You could create an union view of both tables:
CREATE VIEW combined_accounts AS
(SELECT id, twitter_mail AS mail, password FROM twitter_accounts)
UNION
(SELECT id, mail, password FROM my_accounts);

MYSQL>PHP - Trouble with a query relating to function that checks if a table contains a row of user details

I am having trouble with a function that checks if a set of user entered info (username and password) exists within either of the two possible tables where this information is stored.
The first table is the users table. It contains the first set of specific user information.
The last table is the listings table. It contains the second set of specific user information.
I have basically modified my original code to include the new listings table, and hence the trouble coming from within that task. The old code basically counted the number of results in the users table, if the result was greater than 0, then the function returned true, else false.
Now I have been stuck on the best way to go about adding another table to the query, and function. So I have been playing around with a union.
This was the original query:
SELECT COUNT(*) FROM users
WHERE id='$accNum' AND password='$password'
This returned a count of either 0 or 1 based on the info stored in the users table.
This is how I have reworked the query to include a count of the additional listings table:
SELECT count . *
FROM (
SELECT COUNT( * )
FROM users
WHERE id = '$accNum'
AND PASSWORD = '$password'
UNION (
SELECT COUNT( * )
FROM listings
WHERE id = '$accNum'
AND PASSWORD = '$password'
)
)count
This returned a result set of two rows, the first relating to the users table, and the second relating to the listings table. Then a column called COUNT (*) that contained the result count. This is the result set that I see within php myadmin.
Now this is the function:
function databaseContainsUser($accNum, $password)
{
include $_SERVER['DOCUMENT_ROOT'] . '/../../includes/db.inc.php';
$accNum = mysqli_real_escape_string($link, $accNum);
$password = mysqli_real_escape_string($link, $password);
$sql = "SELECT count . *
FROM (
SELECT COUNT( * )
FROM users
WHERE id = '$accNum'
AND PASSWORD = '$password'
UNION (
SELECT COUNT( * )
FROM listings
WHERE id = '$accNum'
AND PASSWORD = '$password'
)
)count
";
$result = mysqli_query($link, $sql);
if (!$result)
{
$error = 'Error searching for user.';
include 'error.html.php';
exit();
}
$row = mysqli_fetch_array($result);
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
The problem that I have, is trying to work out how exactly to check the results to ascertain if the given log in credentials are valid.
I tried this: if (($row[0] > 0) || ($row[0] > 0)) But a var dump on $row showed that only the first row (count of users table) was being added to the array.
So I decided that this was complicated, and a long way to the final result.
So I tried selecting only the id column of the result as in:
...
`COUNT( * )` to `id`
...
$data = mysql_query($sql);
$num_sql = mysql_num_rows($data);
if ($num_sql > 0)
...
But this did not work out for me either.
But in either instance, my hours of trial and error have provided me with no success... So I've decided to seek help from the knowledgeable members of Stack Overflow!
So my question is this, what would be a logical way of going about this task? I am looking for any suggestions, or positive input what so ever here.
As I am fairly new to dabbling with PHP and mysql, if you would like to provide some code to explain your suggestions or input on the matter, it would more than likely help me to better understand the answer.
If you are checking existence only try doing this that way:
select case when
exists (SELECT 1 FROM users WHERE id = '$accNum' AND PASSWORD = '$password') or
exists (SELECT 1 FROM listings WHERE id = '$accNum' AND PASSWORD = '$password')
then 1 else 0
end as itDoesExist
It returns always one row with one column with 1 when record exists in at last one table (else 0).
Do not use count to check whether some specific record/-s exist/-s in table, it's usually slower than simple exists.
Looks like you're going to get two rows in the result no matter what. Try this:
$sql = "SELECT id,password
FROM users
WHERE id = '$accNum' AND password = '$password'
UNION
SELECT id,password
FROM listings
WHERE id = '$accNum' AND password = '$password'
";
Now you can just check mysql_num_rows() to see if there's a match in either of the tables.
There are a couple of ways to go about this; if we are to stick with the approach you started with; you can simplify the query to:
$sql = "SELECT COUNT(1) FROM users
WHERE id = '$accNum'
AND PASSWORD = '$password'
UNION (SELECT COUNT(1) FROM listings
WHERE id = '$accNum'
AND PASSWORD = '$password')";
The reason you are only seeing one result, is because thats the way mysql_fetch_array() works, try doing this to get all results:
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
var_dump($data);
Now you should have both values in there to validate with your conditional statements.

Multiple SQL Searches - OR Command

My users can search for an order by an address right now. What I would like to do is let them be able to search with multiple criteria. Let them search by address, city, state, etc etc.
I have tried using the following code, but it doesn't seem to work.
$sql = ("SELECT order_number, sitestreet FROM `PropertyInfo` WHERE `sitestreet` LIKE '%$street%' OR `sitecity` LIKE '%$city%' AND `user` LIKE '$user'");
$result = mysql_query($sql);
I don't think it's reading the value in $user cause it displays all orders for all users.
How can I make it possible to search for an order using multiple serach values?
Thank you!
Wrap your OR statements in parenthesis so it forms one top-level condition, the user is the other top-level condition:
$sql = '
SELECT
`order_number`,
`sitestreet`
FROM
`PropertyInfo`
WHERE
(
`sitestreet` LIKE "%'.$street.'%" OR
`sitecity` LIKE "%'.$city.'%"
) AND
`user` = '.$user;
Also note, you want a direct match to the user column, use = instead of LIKE. I am assuming that $user is a numeric ID...
How about trying like
$sql = ("SELECT order_number, sitestreet FROM PropertyInfo WHERE (sitestreet LIKE
'%$street%' OR sitecity LIKE '%$city%') AND user LIKE '$user'");
AND has a higher order of precedence than OR (see http://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html for details). You need to wrap your OR statement in parentheses so it get evaluated as one statement, before the AND statement.
SELECT order_number, sitestreet
FROM `PropertyInfo`
WHERE (`sitestreet` LIKE '%$street%' OR `sitecity` LIKE '%$city%')
AND `user` LIKE '$user'
Try:
$sql = ("
SELECT order_number, sitestreet
FROM `PropertyInfo`
WHERE (`sitestreet` LIKE '%$street%'
OR `sitecity` LIKE '%$city%')
AND `user` LIKE '$user'");
You should group the ORs together. The way it is written I believe it is reading it as 'if Street matches, ignore any other conditions (OR), otherwise both city and user must match.
Also G molvi's point is good, unless you're looking for a pattern match, go with =
HTH

Categories