MySQL using WHERE and OR - php

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

Related

How do I check a column that contains a string?

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.

PHP/MSSQL.. Select ID based on username, insert to table based on ID?

I have looked all over and at tons of code and examples.. This is such a small bit of code but I just can't seem to get it to work.
I have dbo.accounts which contains the id, username, password, createtime..
I have a simple form, you type in the username, and I need the select query to return the ID based on the username.
$result = mssql_query('SELECT id FROM dbo.account WHERE name = $username');
The dbo.gamemoney table will just insert some hardcoded info such as an amount of coins for the game..
My problem is that if I use a query as ID = 123, it works, but when I try to grab the id of dbo.accounts by using the username, I get nothing back.
I know it has to be something small, But I have tried to figure it out for so many hours now that I'm honestly lost..
Thanks for your time,
Chris
Since, $username is string type, you have to enclose it in quotes.
$result = mssql_query("SELECT id FROM dbo.account WHERE name = '$username'");
As a better practice would suggest use a try-catch scenario so that you get the exact error log. Try -
$result = mssql_query('SELECT id FROM dbo.account WHERE name = "'.$username.'"') or die('MSSQL error: ' . mssql_get_last_message());
Thanks everyone for the help!
I was able to get it working. Now I'll make sure it's the right way. I had forgot to add,
while($row = mssql_fetch_array($result)) {
$id = $row['id'];
$ip = $row['ip'];
}
Thats why the id was blank. I was missing some code.
Chris

PHP SQL Select From Where

I am having some difficulty running some SQL code.
What I am trying to do is, find a row that contains the correct username, and then get a value from that correct row.
This is my SQL in the php:
mysql_query("SELECT * FROM users WHERE joined='$username' GET name")
As you can see, it looks for a username in users and then once found, it must GET a value from the correct row.
How do I do that?
You need some additional PHP code (a call to mysql_fetch_array) to process the result resource returned by MySQL.
$result = mysql_query("SELECT name FROM users WHERE joined='$username'");
$row = mysql_fetch_array($result);
echo $row['name'];
mysql_query("SELECT `name` FROM users WHERE joined='$username' ")
Just select the right column in your 'select clause' like above.
Edit: If you are just starting out though, you might want to follow a tutorial like this one which should take you through a nice step by step (and more importantly up to date functions) that will get you started.
mysql_query("SELECT name FROM users WHERE joined='$username'")
$q = mysql_query("SELECT * FROM users WHERE joined='$username'");
$r = mysql_fetch_array($q);
$name = $r['user_name']; // replace user_name with the column name of your table
mysql_query("SELECT name FROM users WHERE joined='$username' ")
Read documentation : http://dev.mysql.com/doc/refman/5.0/en/select.html

How to get the result of a select count(*) query in PHP?

I have this query to use in PHP:
mysql_query("select count(*) from registeredUsers where email=".$_SESSION["username"]);
When I use echo to print out the result, nothing gets printed. What exactly is the return value from the above statement?
Your code doesn't include any fetch statement. And as another answer notes, you need single quotes around $_SESSION["username"].
$result = mysql_query("select count(*) from registeredUsers where email='{$_SESSION['username']}'");
// Verify it worked
if (!$result) echo mysql_error();
$row = mysql_fetch_row($result);
// Should show you an integer result.
print_r($row);
mysql_query returns a result resource. You can read the result with mysql_result
$res = mysql_query("select count(*) from registeredUsers where email='".mysql_real_escape_string($_SESSION["username"])."'");
echo mysql_result($res,0);
You need single quotes around the session variable in your query
$result = mysql_query("SELECT COUNT(*)
FROM registeredUsers
WHERE email = '".$_SESSION['username']."' ");
The count query will always return a value, which is 0 if no records are returned, or an integer above 0 if records match it.
It should at least be printing out 0, the query you posted means:
Get the number of records where the email address is equal to the session username
This might not make sense, do you mean to do where username = ".$_SESSION["username"] or something similar?
You may want to echo out the query itself to determine that it is returning what you expect.
mysql_query() returns a resource used to get information from the result set. Use a function such as mysql_fetch_array() to retrieve rows from the result set. In this case, there will only be one row.
It should give you the amount of registere users who have the email address that you provide as the parameter to this query. (Might be a check if the given email address is already registered for another user.)
If the email address is not yet registered, an empty field will be returned. (That might be the reason why nothing gets printed out in your case. Try it with an email address that you are certain of to be in the database.)
$resultemp = mysql_query("select count(*) AS count from registeredUsers where email='{$_SESSION['username']}'");
// Verify mySQL Query Rresult
if (!$resultemp) echo mysql_error();
// Convert mySQL Result for PHP
$counter=mysql_fetch_assoc($resultemp);
$counter=$counter['count'];
// Print Total Employees
echo $counter;
You need to use mysql_fetch_array() to return value in a user defined variable. Then have to print the returned value.
$result=mysql_query("select count(*) from registeredUsers where email='{$_SESSION['username']}'")
$COUNT_NUMBER=mysql_fetch_array($result);
echo "<br>1.Count=" .$COUNT_NUMBER[0];
Try casting it to string before echoing it. As an int, 0 will display as an empty string.

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'")

Categories