How would I echo users who haven't confirmed their email - php

I know how to echo the number of users that have activated their email but it got a bit tricky when I wanted to echo the number of unverified users.
My register system assigns a key in the active column in the members table. If the user activates their email it goes from a random md5 string to 'Yes'
ex: https://imgur.com/a/83BUYTK
Anyways... this is what I got so far:
$result3 = mysqli_query($db, "SELECT * FROM `members` WHERE `active` = 'Yes'");
$unverified_users = mysqli_num_rows($result3);
I just dunno how to echo the number of unverified users instead of the verified users.
Any help is appreciated btw I'm a noob to PHP so go easy on me :P

Answer:
$result3 = mysqli_query($db, "SELECT * FROM members WHERE active != 'Yes'");
$unverified_users = mysqli_num_rows($result3);
I didn't know that != meant not equal to... my bad lol
Thanks to #Barmar

use count(*).
$unverified_users=$db->query("SELECT count(*) FROM members WHERE active != 'Yes'")->fetch_array()[0];
this should be faster than SELECT * because now the db only has to prepare 1 result, the number of matches, instead of preparing a number of results equal to the number of matches.

Related

How to insert a particular value from one database table into another using '$row'?

I am currently trying to make a system which selects a user at random from the table 'users' and appends it to another table 'agreeuser' or 'disagreeuser' depending on whether or not the user has the 'opinion' value of 'like' or 'dislike'. I am doing this by using $row to select the full row where the user has the opinion of 'like', but it doesn't seem to be adding the data stored in '$row[username]' to the 'user' column of the 'agreeuser' or 'disagreeuser' table.
I have already tried storing the '$row['username'] value as a variable and using this in the value aspect of the query, but it doesn't seem to have worked. I have also tried combining the INSERT and SELECT queries and it still has no effect. Can anyone tell me what I am doing wrong, please? :)
if($_SESSION['pageLoaded'] != "true") {
$selectLikesQuery = "SELECT * FROM users WHERE opinion = 'like' ORDER BY RAND() LIMIT 1";
$likeSelectorResult = mysqli_query($userConnect, $selectLikesQuery);
while($row = mysqli_fetch_assoc($likeSelectorResult)) {
$removeCurrentAgreeContent = "TRUNCATE TABLE agreeUser";
$addAgreeUserQuery = "INSERT INTO agreeUser (user) VALUE ('$row[username]')";
mysqli_query($chatConnect, $removeCurrentAgreeContent);
mysqli_query($chatConnect, $addAgreeUserQuery);
}
$selectDislikesQuery = "SELECT * FROM users WHERE opinion = 'dislike' ORDER BY RAND() LIMIT 1";
$dislikeSelectorResult = mysqli_query($userConnect, $selectDislikesQuery);
while($row = mysqli_fetch_assoc($dislikeSelectorResult)) {
$removeCurrentDisagreeContent = "TRUNCATE TABLE disagreeUser";
$addDisagreeUserQuery = "INSERT INTO disagreeUser (user) VALUE ('$row[username]')";
mysqli_query($chatConnect, $removeCurrentDisagreeContent);
mysqli_query($chatConnect, $addDisagreeUserQuery);
}
$_SESSION['pageLoaded'] = "true";
}
I need the username from 'users' to be inserted into the 'user' column of 'agreeuser'. Thanks for any help, and apologies if I'm doing something stupid :)
Why don't you use SQL views to just see needed data in "a virtual table", instead of creating duplicate data?
Views is a very helpful feature.
For example, make a SELECT query to find needed rows:
SELECT * FROM users WHERE opinion = 'dislike'
If this select suits you, just add:
CREATE OR REPLACE VIEW v_agreeUsers AS SELECT * FROM users WHERE opinion = 'dislike'
And make the same for users who agree:
CREATE OR REPLACE VIEW v_disagreeUsers AS SELECT * FROM users WHERE opinion = 'like'
To be honest, I don't understand why do you do random select and insert users only one by one.
In case you want to get only one and random user, just run this query after you've already created views mentioned upper:
SELECT * FROM v_agreeUsers ORDER BY RAND() LIMIT 1
SELECT * FROM v_disagreeUsers ORDER BY RAND() LIMIT 1
Good luck! :)

MYSQL spillover function

I am currently trying to code a Networking website and am stuck at the spillover function stage.Here is how it works, each registered user of the site is only allowed to refer two people into the network (they have a referral link for this). If however,a member gave his/her link to refer more than two people and the registering folk wants to sign up with the link,the following event should occur:
1. PHP should query MYSQL Database to ascertain if the sponsor has referred up to two(2) people, if YES then MYSQL will search for a random sponsor-username to replace the initial sponsor .
2. If on the contrary,MYSQL checks and found that the sponsor hasn't referred two people yet, then MYSQL will proceed to using the sponsor username for the new registering member.
Below is what the database table looks like:
My MYSQL database snapshot
The table name is affiliateuser, the referedby column is where the sponsors are shown for each member,i need member to only be able to appear as sponsor twice (maximum) under the referedby column.
Looking at the table above,the user yelefash2 has referred two people with his link while user mipe305 hasnt referred anyone with his link or username,i need to set a balance and if a third person tries to register with yelefash2's username/referral link,let PHP/MYSQL replace him with a user who hasnt referred two people yet (it could be random pick or otherwise), this will spill over members automatically as referrals onto available spaces, e.g mipe305
I have tried the following PHP codes but it doesn't work:
$ref=mysqli_real_escape_string($con,$_POST['referral']);//data from the referrer webform field//
$result = mysqli_query($con,"SELECT count(*) FROM affiliateuser where username = '$ref'");
$row = mysqli_fetch_row($result);
$numrows = $row[0];
if ($numrows==0)
{
$msg=$msg."Sponsor/Referral Username Not Found..<BR>";//for checking if provided sponsor exits
$status= "NOTOK";
}
$reea = mysqli_query($con,"SELECT username,referedby, COUNT(username) FROM affiliateuser GROUP BY referedby ASC");
$reeeb = mysqli_query($con,"SELECT count(*) FROM affiliateuser where referedby='$ref' ");
$row = mysqli_fetch_row($reeeb););
$refcount = $rowp[0];
if ($refcount ==2 OR $refcount >2)
{$reee = mysqli_query($con,"SELECT username,referedby, COUNT(username) FROM affiliateuser GROUP BY referedby ASC");
$reeel = mysqli_query($con,"SELECT referedby FROM affiliateuser where COUNT(username)<2 ");
$row = mysqli_fetch_row($reeel);
$refpick = $row[0];
}
else
{$refpick=mysqli_real_escape_string($con,$_POST['referral']);}
I know i must be doing something wrong,am kinda new to MYSQL and PHP, any help would be pretty much appreciated
Changed my awnser:
$reea = mysqli_query($con,"SELECT username,referedby, COUNT(username)
FROM affiliateuser GROUP BY referedby ASC");
is not doing anything.but it could be something going somewhere else in the page and its not in this post.
but your result array variable is wrong.
$refcount = $rowp[0];
should be
$refcount = $row[0];
because $rowp is not defined anywhere.... also its row result:
$row = mysqli_fetch_row($reeeb););
is wrong. it should be:
$row = mysqli_fetch_row($reeeb);
at the end, the else condition:
{$refpick=mysqli_real_escape_string($con,$_POST['referral']);}
can be simplified by:
{$refpick=$ref;}
One thing about comparing,
the if ($refcount ==2 OR $refcount >2) should work,
but if (($refcount ==2) OR ($refcount >2)) will guarantee the correct operation.
I personally use || (double pipe) instead of "or" personally.
so I would have wrote it as: if (($refcount ==2) || ($refcount >2)) {

issue with SELECT COUNT(id)

I've been using this command to retrieve the number of the fields which have same email address:
$query = $db->query("SELECT COUNT(`user_id`) FROM `users` WHERE `email`='$email'") or die($db-error);
There are 3 records in users table with the same email address. The problem is when I put * instead of COUNT(user_id) it returns correctly: $query->num_rows gives 3 but when I use COUNT(user_id) then $query->num_rows returns 1 all the time. how can I correct this or where is my problem?
When you use $query->num_rows with that query it will return 1 row only, because there is only one count to return.
The actual number of rows will be contained in that query. If you want the result as an object, or associative array give the count a name:
$query = $db->query("SELECT COUNT(`user_id`) AS total FROM `users` WHERE `email`='$email'") or die($db-error);
And in the returned query total should be 3, while $query->num_rows will still be 1. If you just want the value a quick way would be using $total = $query->fetchColumn();.
As others have said though, be careful with NULL user ids, because COUNT() will ignore them.
Emails have to be uinque in users table. Thus, you need no count at all.
You ought to use prepared statements.
You shouldn't post a code that will never run.
Here goes the only correct way to run such a query:
$sql = "SELECT * FROM `users` WHERE `email`=?";
$stm = $db->prepare($sql);
$stm->execute([$email]);
$user = $stm-fetch();
(the code was written due to erroneous tagging. For mysqli you will need another code, but guidelines remains the same.)
Something like this
$sql = "SELECT * FROM `users` WHERE `email`=?";
$stm = $db->prepare($sql);
$stm->bind_param('s',$email);
$stm->execute();
$res = $stm->get_result()
$user = $res->fetch_assoc();
in $user variable you will have either userdata you will need in the following code or false which means no user found. Thus $user can be used in if() statement all right without the need of any counts.
In case when you really need to count the rows, then you use this count() approach you tried. You can use a function from this answer for this:
$count = getVar("SELECT COUNT(1) FROM users WHERE salary > ?", $salary);
That's the correct behaviour: If you use the COUNT function, the result of your select query will be just one row with one column containing the number of data sets.
So, you can retrieve the number of users with the given E-mail address like this:
$query = $db->query("SELECT COUNT(`user_id`) FROM `users` WHERE `email`='$email'") or die($db-error);
$row = $query->fetch_row();
$count = $row[0];
Note that this is faster than querying all data using SELECT * and checking $query->num_rows because it does not need to actually fetch the data.

MySQL INNER JOIN using an OR whilst logging in

My table structure is as follows:
~ MEMBERS ~
UID (a-i)
NAME
EMAIL
~ COUPLES ~
UID_1
UID_2
PASSWORD
SALT
When a couple sign up, their UIDs get inserted in to the couples table, along with their joint password (and its salt). Now, when logging in, I need to join the tables so I can check the password for either user.
i.e. Find Email Address > See which Couple they are in > Check against Password
This is my current query:
$query = "SELECT * FROM MEMBERS m
INNER JOIN COUPLES c ON ((c.UID_1 = m.UID) OR (c.UID_2 = m.UID))
WHERE EMAIL = '$email'";
(I'm only using * for now as I can't figure out exactly what I need to select for the INNER JOIN to work.)
And the rest of the code on login-script.php is as follows:
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result) == 0) {
header('Location: index.php?msg=error4');
exit();
}
$data = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $data['SALT'] . hash('sha256', $password));
if ($hash != $data['PASSWORD']) {
header('Location: index.php?msg=error5');
exit();
}
else {
echo "Logged in.";
}
?>
If I try and log in, the error message ?msg=error5 gets thrown, which means that the passwords do not match, but I cannot see a problem in that part of my code. I believe it's telling me they do not match because it's not looking in the right table/for the right data, which must be something wrong with my INNER JOIN.
Any help would be much appreciated.
EDIT: I realise now that it would have made a lot more sense to have just put the password and salt in to MEMBERS for both records so I'm only selecting from one table, but the deed is done and I'm curious to see if this is possible.
Actually, I tried your structure and code on http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all and this works for me:
SELECT * from members M JOIN couples C ON uid_1=Uid or uid_2=uid
WHERE email='youremail';
Perhaps the problem is that in the table there is more than 1 couple a person is actually in?
Like:
uid_1, uid_2, pass
1 2 xxx
1 3 yyy
You should either limit it on database side to unique columns or change code, because if you don't, you might be getting more than 1 row as result and you would need to check every couple's password against particular UID.

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.

Categories