MYSQL spillover function - php

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)) {

Related

Like system In Php

Hey I want to create like system in php But I am facing some problem on it ...
How can I create Like system that allow only one like per one user??
This is my code
<?php
if(isset($_POST['like'])){
$q = "SELECT * FROM likes WHERE `username` = '".$_SESSION['recieveruser']."'";
$r = mysqli_query($con, $q);
$count = mysqli_num_rows($r);
if ($count == "0") {
$q1 = "INSERT INTO likes (`username`, `likecount`)VALUES('".$_SESSION['recieveruser']."', '1')";
$result1 = mysqli_query($con, $q1);
} else {
while($row = mysqli_fetch_array($r)) {
$liked = $row['likecount'];
}
$likeus = ++$liked;
$q2 = "UPDATE likes SET likecount='".$likeus."' WHERE username = '".$_SESSION['recieveruser']."'";
$result2 = mysqli_query($con, $q2);
}
}
give me some suggestions
I want only one like per user
In this code every user can give Many likes to another user but I want only one like per one user and I want to display the name of the user who gave like if it's possible
This is only user like code...
I created simliar like system on my website. In my likes table, I had these columns:
Id of comment, that has been liked
Id of user who liked
Id of like (for removal)
When user clicked like, I inserted new row into likes table, with two known values. ID of like was autoincremented.
To show number of likes, I filtered by id of comment and grouped by users id (just to be sure). The number was obtained using count.
select count(*) from likes where comment_id = 666 group by user_id;
Even if you let user insert multiple times, the like counts only as one. But best would be to check, if current user already liked and dont let him do that. For this task, insert on duplicate key update could be used, to spare if exists db request (select).
You should not use the code you posted above. First of all, your code is vulnerable to SQL-Injections and therefore you should use Prepared Statements (https://www.php.net/manual/de/mysqli.quickstart.prepared-statements.php). Second, $_SESSION variables are depricated (https://www.php.net/manual/en/reserved.variables.session.php).
Lets assume you want users only to be able to like a post once. Then, instead of the column likecount you would need a post-id which uniquely identifies the post.
Define the combination post-id and username as a primary key in your database.
Now your code just have to check whether you find the username with the according post-id in the table likes.
In case you do not find the username with the according post-id in the table, you have to INSERT the username and the post-id

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

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.

PHP get variable from on table and then use that variable to select from a second table

I'm building a followers list for a user. I have two tables the first shows the relationships between users and the second table holds every users profile info. In the following code, I first select from the user relationships table to get a variable {$userid1} which is the value of all the user ids that follow the current user. When I echo out {$userid1} I get all the ids of the users who follow the current user but it is one giant connected string. I want to take the variable {$userid1} and use it to pull every one of those follower's user data from the profile table. I want every user's data to show up from the profile table that follows the current user. The code works however only the newest follower's profile data is pulled from the profile table. I was thinking putting the variable {$userid1} into an array and using foreach, but I'm not sure how the syntax would be. Anybody know how it could work? The problem is a variable can only hold one value at a time.
Output of the first query are the iduser numbers from the users following the current user.
e.g. when echoed echo $userid1 . " "; the results are the ids look like this: 45 56 67
I added a space between numbers in the echo statement.
$sql = mysql_query("SELECT * FROM followrelations Where iduser2='$uid' "); //followers from relations table
while($row = mysql_fetch_array($sql)){
$userid1 = $row['iduser1'];
echo $userid1 . " ";
}
$sql = mysql_query("SELECT * FROM profile where iduser=$userid1 ORDER BY username ");//get followers infor from profile using variable
while($row = mysql_fetch_array($sql)){
$iduserf = $row['iduser']; //userid2 requires different var name so program does not get mixed up
$username = $row['username'];
$bio = $row['bio'];
$avatar = $row['avatar'];
echo "
<div style='width:500px;height:100px;padding:20px 20px;float:left;border: solid black 1px;'>
<a href='profile.php?uid=$iduserf'><img src=$avatar height=50px width=50px /></a></br>
<a href='profile.php?uid=$iduserf'>$username </a></br>
</div>" ;
}
You might be looking for subqueries:
SELECT username
FROM user_table
WHERE id IN( SELECT user_id WHERE linked_user_id = 123 )
This is simplefied to be a better example. This will select the username of all users from the user_table, where the ID exist in the subquery.
In turn, the subquery selects all user_id where the linked user has id=123.
The subquery is quite similar to making an array in PHP and use that info for the next query.
Small note: Be carefull with subqueries. They're perfect in my example above, but eg not all servers support a limit in the subquery. This might effect performance. The more complecated functions don't work in a subquery. Try to keep those simple.
You can use something like the following to execute this in a single query:
$id = mysql_real_escape_string($uid);
$sql = <<<SQL
SELECT
p.*
FROM profile as p
INNER JOIN followrelations as fl
ON fl.iduser1 = p.userid
WHERE fl.iduser2 = $id
ORDER BY username
SQL;
$stmt = mysql_query($sql);
while($row = mysql_fetch_array($stmt)){
// Rest of the logic here
}
This will return all the fields in your profile table. Note that the mysql_ extension is deprecated and unsafe - you should not be using it in new code. Take a look at How to replace MySQL functions with PDO? and How can I prevent SQL injection in PHP? for some good practices regarding this.
Found my mistake, the second $sql should be another name (I named it $sql1), and the second half should all be within the first while.
$sql = mysql_query("SELECT * FROM followrelations Where iduser2='$uid' "); //followers session uid
while($row = mysql_fetch_array($sql)){
$userid1 = $row['iduser1'];
$sql1 = mysql_query("SELECT * FROM profile where iduser='$userid1' ORDER BY username ");//get followers infor from profile using variable
while($row = mysql_fetch_array($sql1)){
$iduserf = $row['iduser']; //userid2 requires different var name so program does not get mixed up
$username = $row['username'];
$bio = $row['bio'];
$avatar = $row['avatar'];
echo "
<div style='width:500px;height:100px;padding:20px 20px;float:left;border: solid black 1px;'>
<a href='profile.php?uid=$iduserf'><img src=$avatar height=50px width=50px /></a></br>
<a href='profile.php?uid=$iduserf'>$username </a></br>
</div>" ;
}
}

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.

Ordering retrieved information from a database

I'm creating a feed by retrieving information from my database using nested while loops (is there a better way to do this?).
I have one table called users with all the names amongst other things. The other table is called messages which has messages, the user who posted it, and a timestamp.
$userQuery = mysql_query("SELECT name FROM users");
while ($user = mysql_fetch_array($userQuery, MYSQL_NUM)) {
$messageQuery = mysql_query("SELECT message FROM messages WHERE user = $user ORDER BY timestamp DESC");
while ($message = mysql_fetch_array($messageQuery, MYSQL_NUM)) {
echo "$user[0]: $message[0]";
}
}
The problem is that it doesn't order by the timestamp and I can't tell how it's ordered. I've tried timestamp, datetime, and int types with UNIX timestamps.
EDIT: I should add that the user and message matches up fine, it's just the ordering that doesn't work.
I guess you get your users in more or less random order and "within" one user the sorting is ok?!
use:
$result = mysql_query('select users.name,messages.message from messages join users on (users.name=messages.user) order by messages.timestamp');
while($row = mysql_fetch_row($result))
echo "$row[0]: $row[1]";
That should give you an ordered result (at least if you have a column called messages.timestamp. Check the name ;-)). And all in one query...
For the query, you could create a join
SELECT u.name as name, m.message as message
FROM users u inner join messages m
on u.user = m.user
order by
m.timestamp DESC
As for the second part, I don't see anything wrong with your could. May be you could post some samples of your data to see if that is making any difference.

Categories