PHP Saving Dynamic Radioboxes - php

Im having trouble tring to figure out how to save dynamic radio buttons.
I have a project where i have to use radiobuttons instead of checkboxes.
Basically, there is a database table with "roles" in it ... i.e administrator, user, etc etc etc and these are updateable but the user.
On a specific page, these get spit out with a radio button next to them, like so:
<input name="wfa" type="radio" id="wfa" class="radio" value="1" /><label for="wfa">administrator</label>
These go on down the page, for as many entries there are in the database.
What i need to do is save the checked ones to the database, but being dynamic i cant save each value to a individual row ..... any help?
Someone mentioned serialize, i had a look at the php documentation but it didnt make much sense to me.
Cheers.

You would normally have (at least) three database tables: users, roles, and users_roles (a look-up table). The users table and roles table are self-explanatory. The users_roles table would probably have two columns: user_id and role_id.
So for example, they would look similar to as follows:
Table: users
id INT PRIMARY KEY
username VARCHAR
password VARCHAR
...
Table: roles
id INT PRIMARY KEY
name VARCHAR
Table: users_roles
user_id INT
role_id INT
With this database structure, you can then find out what roles a user has with a query like the following:
SELECT
r.*
FROM
users u, roles r, users_roles ur
WHERE
u.id = ur.user_id
AND
r.id = ur.role_id
This will then give you an array of roles assigned to the current user ID, which you can loop over and output a check box (a better solution in my opinion).
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
printf('<label for="role_%d">%s</label>', $row->id, $row->name);
printf('<input type="checkbox" name="role[]" value="%1$d" id="role_%1$d" />', $row->id);
}
When you submit this, the checked check boxes will then be available as an array under $_POST['roles'], which you can loop over and insert into the users_roles table.

What i need to do is save the checked ones to the database, but being dynamic i cant save each value to a individual row ..... any help?
Why can't you maintain a reference table between roles and users with user_id and role_id? (Let's call this table users_roles_mm.)
When the form is submitted, delete all rows for the current user (user_id) and insert a row with a (user_id, role_id) pair for each checked input (role).
The idea here is that each table—roles and users—are dynamic, as is the reference between them. I.e., users_roles_mm is highly dynamic since it depends neither on the structure of the users table nor the roles table.

Related

Linking SQL Tables - Issue

I would like to link two SQL tables together, both the tables have data entered in them through HTML/PHP forms.
The first table is where the user enters all their details into a form (called system), and the second table is for where a user fills out another form for booking (called users). How do I link these tables together? To show the users booking(s).
I don't know how to get the booking table/form to echo out the user's username into the second table to link them together?
I understand that this does not make sense but would really appreciate some help!!!
Here is the first table's SQL for creating a user account:
And, here is the SQL for creating a booking?:
</form>
</body>
</html>
<br></br>
</div>
</div>
</div>
</body>
</html>
Here is the code that links what the user entered for the booking form (system table) to the SQL database.
Two tables can be "linked" together using JOIN. If you want to list the bookings (rows in the details table), with some user information, you can use LEFT OUTER JOIN or INNER JOIN. (The difference is that with LEFT OUTER JOIN you get all the bookings even if some of them don't have a user. With INNER JOIN you get only the bookings where there exists a corresponding row in users.)
If a column has the same name in two different tables, you can use users.user_uid and details.user_uid to refer to them.
SELECT details.*, user.email, user.first, user.last
FROM details LEFT OUTER JOIN user ON user.user_id = details.user_uid;
Then you maybe want to add a WHERE or ORDER BY and perhaps a LIMIT.
In the users table, there is a user_id (INT) and a user_uid (VARCHAR). The details table has a user_uid (INT). In the example, I was assuming that the user_uid in the details table corresponds to the user_id in the users table because these are both INT. You might want to change the name of some column to make it less confusing. Let's assume you want to rename users.user_uid to "username".
Also, you should add a unique index on the user_id and username, assuming that you want both of them to be unique. For the INT, I suggest you make this the primary key with automatically incrementing numbers and the username, just a unique key:
CREATE TABLE users (
user_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
... ,
username VARCHAR(20) NOT NULL UNIQUE,
...
);
In the details table you probably also want to make the ID a PRIMARY KEY with AUTO_INCREMENT.
A unique key guarantees that there are no duplicates and it also makes lookups on these columns efficient.
If you are just trying to query them together a join should do the trick.
SELECT users.user_first, users.user_last, users.user_email, system.* FROM system INNER users JOIN ON users.user_uid = system.user_uid
In order to store the user_uid value in the system table you need to add a hidden input in your form like this:
<input type="hidden" name="uid" value="<?php echo $_SESSION['u_id']; ?>">
then in your php add
$user_uid = $_POST['uid'];
and insert it when you run your insert query.
INSERT INTO system (date, time, table_layout, user_uid) VALUES ('$date', '$time', '$table_layout', '$user_uid');
Just make sure that your table actually has that column. Once that value is available you should be able to run the above join query.
Let's see. You have two tables, one with user data (users), and one with booking data (details). A "details" row contains an ID of the user linked to that particular row.
Once you know, at least, the ID of the booking, you can get the id of the user like this:
SELECT user_uid FROM details WHERE ID = #specificBookingID
Once you know the user id you can get the user data:
SELECT * FROM users where user_uid = #retrievedUserID
You can do it in one query like so:
SELECT * FROM users where user_uid IN (SELECT user_uid FROM details WHERE ID = #specificBookingID)

How to Create Multiple Rows in Mysql Against One ID (Not Necessarily Primary Key)?

I am developing a reservation system for my school project. It is based on PHP and MYSQL.
The system allows a user to register. After successful login, the users can make a reservation which is stored in the following table in phpmyadmin.
User Table
When a user registers, he gets a user_id. When a user makes a reservation, the data is inserted into the table against the same user_id. But when the user tries to make another reservation, there is no way to store the information of the next reservation.
The question is how do I allow the user to make several reservations?
The user_id is my primary key so I understand it is not possible to create multiple records against one primary key.
Do I have to create a new reservation table and link it to user_id through a Foreign key relationship>? But if my reservation table has a primary key, then several records cannot be inserted against one primary key.
Somehow, each reservation must be linked the unique user_id so that the user can check all the bookings under his name.
Each reservation also needs a unique ID which can be used to cancel/update the reservation.
I believe it must be a basic MySQL question. Something like creating a new reservation table and connecting it with user_ID but I am unable to think of a concrete solution.
Your help is very much appreciated.
Thank You.
Make table users
then at least 2 fields id, name
then make table reservations and its One-To-Many relation so you need to put foreign key in reservation(many side)
reservation
id, name, user_id
then to get reservations from user 1 use select with join
SELECT * FROM reservations r JOIN user u ON r.user_id = u.id WHERE u.id = 1

Storing multiple data in one field (storing data in an array in database)

I have a table called user_thoughts. The table has many columns, one of them being favourited_by.
A thought may be favourited by many different users, but I don't want to create a new row stating that this thought id has been favourited by this user.
I would rather have it that it stores multiple username's in one field. So favourited_by for example can hold data like this:
Alice, Fred, Freddy, Conor ....
All in one single row. I have tried messing around with the data types on phpMyAdmin but cannot figure out how the field can hold multiple data.
What you're asking is the wrong way to do this. You should not serialize the favorites data into a text field for either the user table or the thought table. This destroys the whole purpose of using a relational database like MySQL.
The right way to do this: create a cross-reference table between the user table and the thought table. This utilizes a many-to-many table to store a list of favorites using the primary keys of a thought row and a user row.
Your new favorite table:
CREATE TABLE IF NOT EXISTS `favorite` (
`id` int NOT NULL AUTO_INCREMENT,
`user_id` int NOT NULL,
`thought_id` int NOT NULL,
PRIMARY KEY (`id`)
);
What this does is take the id from the user table and store it in favorite.user_id, then stores the id from the thought table in favorite.thought_id.
To add a new favorite for the user with the id of 123, for the thought with id 456:
INSERT INTO favorite (user_id, thought_id) VALUES ('123', '456');
Get the users that have marked the thought with id 456 as their favorite (using a JOIN):
SELECT u.* FROM favorite AS f
JOIN user AS u ON u.id = f.user_id
WHERE f.thought_id = 456;
And similar to the last query, get the favorite thoughts for the user with id 123:
SELECT t.* FROM favorite AS f
JOIN thought AS t ON t.id = f.thought_id
WHERE f.user_id = 123;
The ideal way to handle this is to map it to another table, however you can just store it as json.
MySQL 5.7 even includes JSON as a data type allowing easier filtering and manipulation.
https://dev.mysql.com/doc/refman/5.7/en/json.html
You can put json into any text field however if you don't need to search it, etc.

Associate a database row with a logged in user

I am currently creating a website through Joomla (creating a module) that is a members only site.
When members log in, I would want them to see their points (think about it like an airline flyer points site) which are unique. I have stored the points in a table in the database.
I have two tables:
#__users (the basic user table)
#__smiles_users (this stores the username, points etc etc)
Both tables have one similar column and this is "username".
I thought it would be wise to do it like this in an MYSQL query.
Connect to MYSQL
Find out the username that is logged in through #__users
Find the matching username in #__smiles_users table
Echo results that are in that specific row (that contains the correct username)
I have connected to MYSQL, echo the results, but I had to specify the WHERE function.
There are two main approaches to accomplish this:
You can perform two separate queries for every table and join them via a PHP associative array:
SELECT * FROM `__users` WHERE `username` = ?
And store the result to a var:
$user = $result->fetch();
Then do a second query for the remaining data of such user:
SELECT * FROM `__simles_users` WHERE `username` = ?
And join the data programatically like this:
$user_smiles_data = $result->fetch();
foreach($user_smiles_data as $key => $value) {
$user[$key] = $value;
}
Or something like this if you don't want to perform two different queries:
SELECT * FROM `__users`
INNER JOIN `__smiles_users`
ON `__users`.`username` = `__smiles_users`.`username`
This merges both tables by the username field at query time. The result will include all the fields of the two tables on a single row for the same username.
You are probably going to want to create a foreign key from one table to the other.
For example in SQL:
ALTER TABLE #__smiles_users
ADD FOREIGN KEY (username)
REFERENCES #__users(username)
This creates a link from one table to the other to ensure data integrity.

PHP script for adding friends

Well I'm trying for last 5 days to create simple register, confirm, login PHP script, which is for assignment at UNI, but thing which I'm trying for last 5 days and it's not working is adding friends into friend list. Kid a like Facebook but much much simpler, it's for Android game we got as group assignment.
I have one TABLE users where I have fields ID, username, password, email, friends.
Into field friends I would like to save multiple values as ID's of your friends. To retrieve in game some of user information.
This db and tables are on MySQL and INSERT or UPDATE are not working for me, INSERT is creating new record and can't insert only to one column of existing record and UPDATE can't just insert value but will delete old one and insert new one in.
Seeing as this is a many-to-many relation (if I'm correct) so it'd be smart to create a seperate table that records this.
Table: Friends
userID
userID2 (or friendID)
Which you can fill.
For more info: http://www.singingeels.com/Articles/Understanding_SQL_Many_to_Many_Relationships.aspx
Normally you would add a freinds table with the fields:
user_id
friend_id
where both fields are references to the user tables id field.
If you - for some reason - need it to be a field in user table serialize the id values and save them there.
ATTENTION: you won't be able to easily join the tables and there is no automated possibility to keep integrity. If a user is deleted none of the references to this user in friends field will be deleted. This would all be possibile with the secondary friends table and foreign keys.
What you've described here is a many-to-many relationship between people and their friends. The canonical way do implement this in a relational database is to use a pivot table in which each row represents a "friendship" between two people. You'd have two fields to hold the IDs:
users table:
id, name, email, etc.
friendships table:
user_id_1, user_id_2
Then if user 1 is friends with user 2 and user 3, you'd have records (1,2) and (1,3) in the friendships table. You can treat these as reciprocal relationships if you like, or you can require a (2,1) record to denote that user 2 is also friends with user 1.

Categories