I am trying to learn about Foreign keys and being able to associated data from one table to another. So I have a users table and a cards table.
The user table has 'user_id', 'username' & 'email'.
The card table has 'card_id' & 'name'.
what I am looking to do is associate a card form the card table to the users. so for example if the card table has Card1 inside and user1 wants that card (or more) assocaited with them how would I use the foreign key to do this.
Here is how I am selecting and showing my users at the moment:
<?php
$sql = "SELECT user_id, username, email_address FROM user";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
$row["username"] . "<br>",
$row["email_address"] . "<br><br>";
}
} else {
echo "0 Members";
}
$conn->close();
?>
I understand inside of the user table I will need to another another cell 'card_id' but not sure on which data type this should be?
Based on your question and on your following comment:
so the cards table is reffering to playing cards. A user can collect
the cards so they become a part of the users deck essentially. I want
a way for the card to be associated to the user.
I believe you can achieve that in 2 ways, depends on further scenarios in your game/script.
Scenario 1:
In case one card can be belong to only one user.
Add a new field to the cards table.
`user_id` INT(11)
When a user collect a card, just update that field so it will store the user's id.
Scenario 2:
In case one card can be belong to many users.
Create a new table called users_cards:
users_card
- id (INT)
- user_id (INT)
- cart_id (INT)
When a user collect a card, insert a new record to that table with both the card's id and the user's id.
Related
I have 3 tables 'Company', 'Company_Officer', 'Officer'. Companies are unique and Officers are unique but officer could work for multiple companies with different roles therefore Company (1) - (many) Company_Officer (many) - (1) Officer.
Company:
Company_ID
Company_Name
Company_Officer:
Company_Officer_ID
Company_ID
Officer_ID
Officer_Role
Officer:
Officer_ID
Officer_Name
Here is how I fill out Company & Officer tables
foreach($YQL->getConstituents() as $key=>$companyName){
$company[$key] = new Company($companyName);
if($company[$key]->getCompanyFound()==true){
array_push($Company_Details,array($company[$key]->getCompanyName(),$company[$key]->getCompanyNumber(),"FTSE 100"));
foreach ($company[$key]->getCompanyOfficers() as $officer){
array_push($Officer_Details,array($officer[0],$officer[2]));
}
}
}
$Company_Details = array_unique($Company_Details, SORT_REGULAR);
$Officer_Details = array_unique($Officer_Details, SORT_REGULAR);
$DAO->insertMultiOnDuplicateData("Company_Details", array("Company_Name","Company_Number", "Company_Index"), $Company_Details, array("Company_Index"));
$DAO->insertMultiData("Officer_Details", array("Officer_Name","Officer_Resigned"), $Officer_Details);
If a record of Officer/Company already exists only additional fields would be updated the whole row will not be inserted again since Officers/Companies are unique.
But I have no idea how to fill out Company_Officer since it requires Company_ID & Officer_ID which I don't have while executing this code is there a simple solution to this problem? Should I just insert Officers/Companies then get them all back from database to receive IDs of companies and officers and compare to arrays that I have used to update the database?
Good Afternoon.
I am trying to create a list of all the Users in my database that contain data in a certain table.
I have 2 tables.
USERS - Contains the name of all the users
DATA - Contains data relative to the user (IT isn't called DATA obviously).
Let's say i have 3 users:
Pedro;
Armando;
Henrique;
Pedro has data in the second table. "Armando" and "Henrique" Don't have any data in the other table.
I want to print the name of all users that contain data on the "data" table.
I tried to do this:
$query=mysql_query("select nome from users where nome <> 'admin' ORDER BY nome");
while ($whatever=mysql_fetch_array($query, MYSQL_ASSOC)){
foreach ($whatever as $w){
echo $w. ' '; //$w contains the name of all the users.
$queryy = mysql_query("select id from users where nome='$w'");
$idd = mysql_fetch_array($queryy);
}
}
$conta=count($idd);
for ($i=0;$i<$conta;$i++){
echo $idd[$i];
$queryyy=mysql_query("select * from pp where id_user='$idd[$i]'");
}
On the table "pp", the field is id_user, as it is stated there, instead of "id" like on the users table.
I don't know how to proceed from here on out, since i am new to php.
Thanks
A simple JOIN can get this for you -
SELECT USERS.name
FROM USERS
JOIN DATA
ON USERS.name = DATA.name
I have a system where a PHP script uses MySQL to get info based on a user. Then, based on that information, a certain button will be displayed. The database that is being called has columns:
id
user_one
user_two
This is meant to check if two users are friends. However, my problem is that if a user has more that 1 friend the script only works for the 1st friend.
$select_friends_query = mysql_query("SELECT friend_id FROM friends WHERE user_id = '$user'");
while($friend_row = mysql_fetch_assoc($select_friends_query)) {
$friend = $friend_row['friend_id'];
}
if ($username == $friend) {
$addAsFriend = '<input type="submit" class = "frnd_req" name="removefriend" value="Disassociate">';
}
else
{
$addAsFriend = '<input type = "submit" class = "frnd_req" name = "addfriend" value = "Send Associate Request">';
}
}
}
Then I have echo $addAsFriend later.
I recommend that you change your database design as follows:
User_id, PK
Friend_id, PK
PK = Primary Key. Primary key is the key under which records are stored. It must be unique. The reason we are making it a COMPOUND primary key (two fields make up the PK instead of 1) is because it is impossible for a user to be friends with with the same user Multiple times. Mysql will ensure this does not happen and you won't have to do it on the application level.
Thus, if user "12" and user "25" become friend you should two records:
(12, 25) and (25, 12)
You must have two records because data means literally "user this has friend that." Is it possible for two users to have a one way friendship - not really BUT you may want to one day expand this table to include preferences on the relationship type between the two friends and you would want to distinguish between A -> B and B -> A relationship.
So let's get to the meat of the question. To query mysql to find all friends to a specific user we do the following:
$sql = "SELECT friend_id FROM friends WHERE user_id = 25;";
$query = mysql_query($sql, $connection);
// Loop through all friend records
while ($row = mysql_fetch_assoc($query)) {
$friends[$row['friend']];
}
I don't use procedural code (mysql_query) and instead use mysqli with OP: $mysql->query(). basically, I am not 100% sure if this code will run but it gives you a guide to get started.
At the end of the program, you will have an array "friends" with keys that tell you the friend ids. So "friends" -> 12, 21 could be a potential data set.
You have to look over all results. Like the while loop example in http://www.php.net/manual/en/function.mysql-fetch-assoc.php
I am trying to make my voting system work. I have 3 databse tables:
users, posts, votes
the table users has field username as the primary key. table post has post_id as the primary key. (there are more fields but they don't affect the question/problem)
In the votes table I have 3 fields: username, post_id, vote. vote is enum ('positive', 'negative'). What I'm trying to achieve is that if a user votes for a specific post that is displayed on a page, the query: INSERT INTO votes ('username','post_id','vote') VALUES('$user_name','$post_id', 'positive'); will be executed.
It works if lets say user 123123 has not voted for any post at all yet. When this user votes lets say for post 1, this query works fine. But then if this user wants to vote for a different post, (his vote gets counted - I just copied the part of the code that doesn't work, the rest of it is fine and working) the insert query get's not executed. If user abcd wants to vote for a specific post, this works fine again, but only once. It seems to me that there is some kind of problem with the database, so that there can be only one entry with the same username or post_id. How can I fix this if I want one user to be able to vote for multiple posts? Is there a better strategy for this?
if($runloggedin->num_rows == 1)
{
// If there was no vote for the current posting, then execute this query
$query = "SELECT * FROM posts WHERE post_id='".$post_id."' AND user_name='".$user_name."'"; //get username and the post id
$result = $mysqli->query($query);
$query1 = "SELECT * FROM votes WHERE post_id='".$post_id."' AND username='".$user_name."'"; //check if there is a vote for this post already
$result1 = $mysqli->query($query1);
if ($result->num_rows == 1 && $result1->num_rows == 0)
{
$vote = "INSERT INTO votes ('username','post_id','vote') VALUES('$user_name','$post_id', 'positive')"; // this isn't working. everything else seems to be working (still test it more)
$savevote = $mysqli->query($vote);
$addvote = "UPDATE posts SET posvotes=posvotes+1 WHERE post_id='".$post_id."'";
$runvote = $mysqli->query($addvote);
echo "Thank you for your vote";
}
}
Without seeing how your votes table was created, my guess is that username has been set up as the primary key. This will make the first INSERT work, but all future ones fail. What you need to do is change it to have username & post_id be the primary key
ALTER TABLE `votes` DROP PRIMARY KEY , ADD PRIMARY KEY ( `username`, `post_id` )
I was coding a script for the following model:
Suppose there are 5 events. For the users to register for the events, they need to input some details. Registration is in the form of a team, but the number of members in each event are different.
In my sql table events there is a row members which stores the number of members for all the 5 events.
Using the data stored in the members row, I can run a for-loop for the HTML display of table, where the user can input his and his team details.
But I'm confused as to how I will code the php part? I know php, getting the information and storing them in the sql database, but in this particular case do I have to code separate php script for all the events as the number of members will not be the same.
EDIT#1
The events are for example. :
**event1**: number of members: 5 (mem_1, mem_2, mem_3, mem_4, mem_5)
**event2**: number of members: 3 (mem_1, mem_2, mem_3)
**event3**: number of members: 2 (mem_1, mem_2)
**event4**: number of members: 4 (mem_1, mem_2, mem_3, mem_4)
**event5**: number of members: 6 (mem_1, mem_2, mem_3, mem_4, mem_5, mem_6)
The mem_x fields store the name of the member.
So how can I code a single php script for the registration. Do I have to make separate functions for all the events as the number of members are different for the events.
You check the inputted data to make sure that the number of members entered matches the number of members allowed for the event.
Then you loop over the data adding each (new) member to your members table, and the member_id and event_id to your members_events junction table (adding a number of rows equal to the number of members).
If it were me, I'd have my table with the following fields:
Column Name Example Value
member_id [auto increment]
member_group Step1
member_type text
member_order 1
member_title First Name
member_field_name fname
member_default enter first name
member_max_length 25
Then, in PHP, you can do a query like:
$fields = mysql_query("Select * From [member table] Where member_group = 'Step1' Order By member_order;")
while ($field = mysql_fetch_assoc($fields)) {?>
<label for="<?= $field['member_field_name']; ?>">
<?= $field['member_title']; ?>
<? switch ($field['member_type']) {
case "text":
echo "<input type=\"text\" name=\"".$field['member_field_name']."\" value=\"".$field['member_default']."\" />";
break;
}?>
</label>
<?}
Then, when processing the page, just get the list of fields again from the database (for the field name) and process the page.
You don't need different functions depending on the number of members.
You could for example store all the inserted members in an array and then do something like
foreach($members as $member){
mysql_query ( "INSERT INTO members (name,eventID) VALUES (".$member['name'].",".$members['eventID'].")" );
}
where $members is the array containing the members names.
Is this what you wanted to know?