Updating membership MySQL database automatically in PHP - php

I have set up the database with all the various fields and can carry out all the necessary registration and logins etc. – so far so good!
What I need to do now is as follows:
When a new member attempts to register he/she must provide the email address of an existing member (like a sponsor, as it were). If the sponsor email is a fake or doesn’t exist in the data base, the application to join is rejected.
If genuine, I need to automatically retrieve the record of the sponsor and update his/her record by putting the new member in one of two possible fields. Each member is allowed to sponsor two and only two new members. So if the sponsor has no new members, field-A and field-B will be empty, therefore the email of the new member will be allocated to field-A. If, on the other hand there is already an entry in field-A, the new member email will be stored in field-B. If both are already filled a warning will be flagged and the sponsor will be refused permission to introduce the “third” new member.
I would be most appreciative of any help with this, having spent the best part of a week researching without success. I am sure there is a fairly simple answer from an expert on this wonderful site.

Fang Man,
I would not use 2 columns for this.
I would create a new table member_sponsors for instance.
It would consist of:
id - auto incrementing primary index
sponser_id - id of sponsor
memeber_id - id of new memeber
sponsor_date - date member was sponsored?
This way you can simply query this table and check if it contains less then 2 (or if down the road you want to increase this value this can be done easily).
Then just add the info to this table.
Hope this concept makes sense and is helpful to you.
Tim

Assuming your table with the existing members is called "members" with the following structure:
Field name Type
------------------------------------------
id int (primary, auto)
name varchar
email varchar
submember1 int
submember2 int
When the registration request is submitted, I assume you'll have a value like "sponsor_email" to check. After sanitizing this value and ensuring that it is an email address (hint: use regex), grab the info about your member:
SELECT
id,
name,
submember1,
submember2
FROM
members
WHERE
email = "'.$sponsor_email.'"
... and make sure the user signing up has a valid member's email address. If so, check to see if that member has an open slot:
if ($member['submember1'] > 0 && $member['submember2'] > 0) {
// add warning to sponsor, reject the signup
}
Now, you'll have to figure out which slot to put this new signup in - if $member['submember1'] is greater than zero (already filled), the signup goes in slot 2, else slot 1.
A much more flexible way is to add an associative table linking members and the sponsors, do this instead of adding fields to track this in the member table. There are a few advantages to this approach, most importantly that if you decide you want to increase the limit 5 submembers instead of 2 (for example), you can easily change a few small spots in the code without touching the database structure. Done "your way", you would have to change the database AND the code...
if ($member['submember1'] > 0 && $member['submember2'] > 0 && $member['submember3'] > 0 && $member['submember4'] > 0 && $member['submember5'] >0) {
// add warning to sponsor, reject the signup
}
... yuck! Plus, this will get hairy deciding which slot to put the new signup in. An associative table does not have this problem. Using the associative table route, you still have the members table:
Field name Type
------------------------------------------
id int (primary, auto)
name varchar
email varchar
... and then you have a member_sponsors table:
Field name Type
------------------------------------------
id int (primary, auto)
sponsor_id int
member_id int
The member_id field holds the id of the "sponsoring" member, the sponsor_id field holds the id of the "sponsored" member.
Using these tables in the signup process, again, get your member, but also do a join and count of their current sponsors
SELECT
members.id,
members.name,
COUNT(member_sponsors.id) AS sponsored_count
FROM
members
LEFT JOIN
member_sponsors ON
member_sponsors.member_id = members.id
WHERE
email = "'.$sponsor_email.'"
GROUP BY
members.id
Now, as long as the email matches, you will have a row with the id, name, and current number of sponsored members the given user has. Your php would now look like this:
$limit_on_sponsorships = 2;
if ($member['sponsored_count'] >= $limit_on_sponsorships) {
// add warning to sponsor, reject the signup
}
$limit_on_sponsorships can come from anywhere, make it a constant, make it a database setting, etc... all you have to do now to make a change to the number of allowed sponsors is modify that one value. Using this method makes your code more flexible and ready for changes.

Related

How can I show results in a select input, based on values shown in a seperate table?

I have three tables, and I'm just looking for a way to make this work.
tbl_campaigns has the columns "id" and "campaign". This one is fairly straight forward, it's just campaign names with an ID number that is auto-incremented so they have unique IDs.
tbl_users has an "id" column so each user has a unique ID number, standard stuff.
tbl_permissions creates a new row whenever a new user is created. This means its "id" column has unique ID values that match to the ID of a user in 'tbl_users'. The columns have been named to match the ID value of a campaign each time a new one is created, for example, the column "campaign_1" is relevant to the campaign in 'tbl_campaigns' with the ID of 1. The idea is this table data is filled with either 1's or 0's.
If a row with the ID of 1 has the number 1 for the column "campaign_1", then the user with the ID of 1 is approved for the campaign with the ID of 1 in the campaign table. If it were 0 then they're not approved for it. The same logic applies for columns "campaign_2", "campaign_3" etc..
Anyways, the issue I'm having is displaying this information on a front-end, as I only want the user to be able to see the campaigns they are approved to run in a drop-down list. When the user is logged in it stores their User ID in a session, I'm not sure if there's a way around it with this method.
Is there any way to get around this? Please note I've done this in procedural PHP as I'm still in my early days, so if anyone has a solution along these lines it would be much appreciated. Sorry if it's a little confusing. I am aware it's a bit ham-fisted, but I just want it to work first.
I believe that your schema needs to be improved, as the table structure should not have to change every time that you add a new campaign.
keep tables tbl_campaigns and tbl_users as they are
create table tbl_permissions with 4 fields (id, user_id, campaign_id and permission)
To check if a user has permission use a query like this:
SELECT permission FROM tbl_permissions WHERE user_id = ? AND campaign_id = ?
So, every time you create a campaign add a corresponding record to the tbl_permissions table. No need to add a new column.
I think the best practice to do this is as follows:
- Create HTML to show to the user(if you don't have it, let me know so i can work on one you can use)
- Create JS archive that will be in charge of calling PHP file and show the result in your HTML(if you don't know how to make it let me know so i can help you)
- Create PHP file, this is going to be in charge of consulting your data base and give the result disired for your select (if you don't know how to make it, let me know)
It is pretty easy to make this work, let me know if you need more help.

Query and Display referrer details

I have a website built with PHP and mysqli and now I am building administration panel for this website. I am facing some difficulties for querying and displaying referral data I do not have any idea how to do it.
I have a table called user_registration and the fields include, user_name, email, password, referrer. Whenever any of the registered member is referring others the referrer username will be saved in the field "referrer".
Now what I want is to fetch only the rows of the members who has referrals (means referred by my registered members) and also want to count how many referrals a member have and echo it.
For example: I have 20 registered members and from it 5 members have some referrals so I want to query and echo those member's username who has referrals and also count how many referrals they have:
Member's Username Total Referrals
user7 8
user6 6
user1 5
user9 3
user5 2
My solution would be. Make a new column in your user table like "totalreferrals". In this way you can easily keep track of the amount of people they have referred. You could also make a new table "referral". In here you would save the referrals name, the new persons name and a timestamp or something. Now it is even possible to make queries for different periods.
I think that you need to rethink about your database setup, instead of trying to make way to complicated queries, to make your database work.
I am just giving an idea in short which may help you to complete your project -
Suppose your site URL is http://yoursite.com.
1) Whenever a user is registered, you can generate a random key for that user and save it in the database for that particular user. e.g. user1 => abc123
2) Now, you can tell your user (may be on a page after their successful registration) that his/her referrer id is http://yoursite.com/?ref_id=abc123 (by appending it as a new parameter)
or if your register page is http://yoursite.com/register then http://yoursite.com/register/?ref_id=abc123
3) Now, they can share this link to their friends, colleague etc to whomever they want.
4) Now, suppose if a person (may be his friend to whom the user1 referred) clicks on the above link. He will land on your site with the parameter 'ref_id' appended.
5) Just using $_REQUEST['ref_id'] or $_GET['ref_id'], capture its value and store it in a SESSION variable. This you can do on the main page of your site e.g. index.php
6) Now, if that user does the registration, you can make an entry in the database that he has been referred once by the user who has referrer id abc123 i.e. user1.
7) So, you can add count = 1 for user1. If more people come with the same value for the 'ref_id' parameter, you can keep on increment the count.
8) If no such parameter is exists when user lands on your site, then that means he has not referred by anyone. So, that means he is the first kind of user i.e. user in point no. 1).
9) You may also need to take care of some validation part at some places in this.
EDIT:
SELECT user_name, referrer FROM user_registration WHERE referrer > 0;
Assuming that you have a proper insert query ready which gives you the result as you shown the table in your question.

Excluding Row From MySQL Query If ID is Blocked

I'm sure this is MySQL 101 and I apologise if the answer is simple, but I'm a little stuck so here I am.
I have a table of users, named 'site_members' with various fields but importantly, each with a unique id.
I also have a very simple two-field table, named 'blocked_members' which contains the id's of users who have been blocked by the logged in user, which is simply set up to store the user id of the person blocked, and the user id of the blocker:
Field 1 | Blocked
Field 2 | Blocker
Before I run a query on the 'site_members' table, I run a query on the 'blocked_members' table to find out if the current logged in user appears in either column:
$sql = "SELECT * FROM blocked_members WHERE blocker = '$loggedin_id' OR blocked = '$loggedin_id' ";
What I need to do next is get the corresponding user id from each row the logged in user's id appears in, and exclude that(those) from my main query on the 'site_members' table, but I do not know how I would go about this?
Can anyone help or point me in a cleaner direction?
You use a subselect.
SELECT * FROM whatever WHERE posting_user_id NOT IN
(SELECT blockedid FROM blocklist WHERE blockerid = <<current user viewing the page>>)
while inserting the ID of the User whose blacklist shall be applied.
You can do inner query... you cann do
... WHERE blocker NOT IN (SELECT bloker_id FROM ...)

PHP/MySQL insert into multiple data tables on submit

I'm building a web application in work and I have a form where users can register certain types of information.
Username | Password | Company
Now I'm unsure how to approach this. What I want is when the user submits that registration form Username, password and company get written to one data table(user) BUT because Company, in the user data table, is a foreign key reference I need Company to be written to a separate datatable(company) as a Primary Key (and of course username to be written as a FK reference as its a 1 - 1 relationship).
I'm not looking for a coded solution from you guys because I know my PHP and MYSQL I'm just looking for some pseudo code algorithms to get the creative juices flowing!
EDIT: I AM USING POSTGRESQL not MYSQL but I'm pretty sure there's little difference except port numbers and small syntax changes
assume first column is id:
Save Company $mysqli->query("INSERT INTO company VALUES (NULL, '$company_name')";
Get id of this item. $company_id = $mysqli->insert_id;
Save User with this id $mysqli->query("INSERT INTO user VALUES (NULL, '$username', '$password', '$company_id')";
Get user's id $user_id = $mysqli->insert_id;
Update the company with it: $mysqli->query("UPDATE company SET user_id = $user_id WHERE company_id = $company_id)";
Begin to insert your compagny in your table compagny.
Get back the id. (There is a sql requete like LastInsertId)
Insert the user/password/IdCompagny in your table user.
EDIT : some help : http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
Some questions:
why is User:Company == 1:1? If I and a coworker join your site, do we need to pretend to work at different places?
if companies can have more than one employee, what kind of validation will you employ to combine variations on company names (e.g. IBM vs International Business Machines)?
what if a user is unemployed?
If Company is a nice-to-know datum rather than a required-or-things-break datum, I'd probably sign up my user first. Then, when the user logs in you can nag them for additional information. This has the added advantage of making user registration less onerous for the user.
A use case:
user submits username and password
filtre input for bad stuff and validate for duplication, suitability
save to db and retrieve user PK
load 'additional info' page and set a session var as a "nag" flag
-if user chooses not to fill out add'l info, nag flag can trigger reminder behaviour
add autocomplete to Company field so that user can use existing Company table entries
process form and save to db
either add company and associate user
or just associate user
unset session nag flag so your website won't continue to nag

PHP/MySQL website with users table, need to add usergroup functionality

I have working website in PHP with a MySQL backend which has several tables for different purposes.
This site is based on different parts or 'environments' like a bugtracker, project management, etc.
There is one central 'users' database which has all the users with the associated details in them.
In each of previously mentioned 'environments', which all have their own set of tables, it is possible to specify a user ID in certain fields.
e.g. the bugtracker table has a column called AssignedTo which contains the user ID's of users to whom bugs have been assigned.
The field type of these 'user ID' columns (like the AssignedTo example) is the same as the UserId field in the central users table, which is an unsigned, zerofilled INT(5) field.
Now I have a request from the users of this site to also allow to specify user groups in certain of these user ID fields.
So again reffering to the AssignedTo example, it should now be possible to also assigned a bug to a user group, instead of a specific user.
What's the best way to do this regarding the PHP scripting and the database layout?
Now I have all these fields set to the same type as the UserId of the central users table, which is INT(5).
However my UserGroupId field in the UserGroups table, is of a different format, INT(3).
I could make this field also into an INT(5) field, but that would not solve the 2nd issue I'm having: how to see whether the AssignedTo value is reffering to a specific user, or to a usergroup.
I was thinking about make the UserGroupId field start from 99999 and counting downwards, while the UserId field is starting from 00001 and counting upwards, thus assuming that if the AssignedTo starts with 9, it's reffering to a usergroup.
But this doesn't seem like a clean solution to me...
Any better ideas?
Thanks!
I think I understand what you are trying to say. I have a question. Can a user be in multiple UserGroups?
I would probably add a column in the bug table that says whether the AssignedTo value refers to a UserID or a UserGroupID.
Create a separate table for UserGroups.
If Users can belong to multiple groups, create an association table like: AssociationID, UserID, UserGroupID.
Otherwise if each user can only belong to one group, just add a UserGroupID column to the Users table
If I am understanding correctly, my solution would be to instead of having an AssignedTo column pointing to either a user or a user group, I would create two columns. One pointing to the user id and another pointing to a user group id.
Actually a colleague at work came up with the following solution which I really like:
Change the UserId and UserGroupId field types from INT(5) to INT(4). And leave the different fields like AssignedTo set to INT(5).
Now in the PHP code I can add a prefix number to either the 'UserId' or 'UserGroupId' value, this prefix number can be used to determine if the value is reffering to a UserId or a UserGroupId value.
So if the AssignedTo field is '10005' it means it's a 'user' with 'id: 0005'. Also to prevent having to update all existing records, values which have a '0' at the first position will be considered users
The advantage over using positive/negative values here is that in both the Users and UserGroups tables I can still use a positive 'Id' field which can be left to autoincrement. As far as I know auto-incrementing is not possible with negative values

Categories