Store multiple value in same cell - php

I am trying to add a "Kudos" system in my website. I am using phpMyAdmin. When a user press a button, it gives kudos/like on a image. The table contains these columns: id, user, photo and kudos. Then I am thinking about returning the count of how many has gives kudos to that post. I am not sure how to do this, but I am thinking about store the users id inside the kudos column. But how can I store multiple names inside the cell? For example if James, Jack and John give kudos on the same post, it will say Number of kudos: 3.. Any suggestions?

You should make a separate table with columns user_id and image_id. That way every row represents a kudo.
By making both columns a primary key (combined called a composite key), the combination of both creates a unique key. That way a user can't give a kudo to the same image twice!
Because I don't know the specifics of your other tables I assume you have two tables. users with primary key id, type BIGINT(20) and image with primary key id, type BIGINT(20). If that's different you will have to change the CREATE TABLE statement accordingly.
CREATE TABLE IF NOT EXISTS kudo (
user_id BIGINT(20) NOT NULL,
image_id BIGINT(20) NOT NULL,
PRIMARY KEY (user_id, image_id),
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
FOREIGN KEY (image_id) REFERENCES image (id) ON DELETE CASCADE
);
If you use REPLACE INTO rather than INSERT INTO you won't get errors when inserting a duplicate. https://dev.mysql.com/doc/refman/5.7/en/replace.html
To save a kudo from user_id = 1 for image_id = 1:
REPLACE INTO kudo (user_id, image_id) VALUES (1,1);
To count all kudo's for image_id = 1
SELECT COUNT(*) AS kudo_count FROM kudo WHERE image_id = 1;

Related

PRIMARY KEY for a table with 2 columns used for counting?

I have several tables that store 2 values, for example one of them is a table likes that stores the id of the user who liked user_id (Auto increment, Primary key) and the post_id (Auto increment, Primary key).
"INSERT INTO likes (user_id, post_id) VALUES (value, value)"
Then to i use a count on the post_id and show them back to the page.
My question is do i need another unique Primary key(AI) on the likes table or do i make post_id as a Primary key since from what i know is faster to do select and counts on keys?
Create one unique index on two user_id and post_id field

php MySql 2 column as index and 1 as another index?

I'm using php and i have a table that have 2 column of varchar , one is used for user identification, and the other is used for page name entry.
they both must be varchar.
i want to insert ignore data when user enter a page to know if he visited it or not, and i want to fetch all the rows that the user have been in.
fetch all for first varchar column.
insert if not exist for both values.
I'm hoping to do it in the most efficient way.
what is the best way to insert without checking with another query if exist?
what is the best way other then:
SELECT * FROM table WHERE id = id
to fetch when the column needed is varchar?
You should consider a normalized table structure like this:
CREATE TABLE user (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);
CREATE TABLE page (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);
CREATE TABLE pages_visted (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id INT UNSIGNED,
page_id INT UNSIGNED,
UNIQUE KEY (user_id, page_id)
);
INSERT IGNORE INTO pages_visted (user_id, page_id) VALUES (:userId, :pageId);
SELECT page_id FROM pages_visted WHERE user_id = :userId;
I think you want to implement a composite primary key.
A composite primary key tells MySQL that you want your primary key to be a combination of fields.
More info here: Why use multiple columns as primary keys (composite primary key)
I don't know of a better option for your query, although I can advise, if possible:
Define columns to be NOT NULL. This gives you faster processing and requires less storage. It will also simplify queries sometimes because you don't need to check for NULL as a special case.
And with variable-length rows, you get more fragmentation in tables where you perform many deletes or updates due to the differing sizes of the records. You'll need to run OPTIMIZE TABLE periodically to maintain performance.

Search in MySQL foreign field

I'm fairly new to PHP and MySQL.
I have two tables as follows:
1.`users`: `id`//primary key
: `name`//user's name
2.`events`: `u_id`//index key and foreign field to users' id
: `u_name`
A user will input an id in a form. That id will be searched in the users table and the relevant details will be taken and inserted in the events table.
I've created the foreign fields and and till now I made a function that took id as a variable and returned details from the users tables as variables which I then inserted in the events table. But then, it meant using "a lot" of variables and I thought what was the use of foreign field.
I'm still learning PHP and don't know how to find and insert using FOREIGN fields from one table to another. I just know how to create foreign fields. Please help.
Is this what you're talking about?
This is how foreign key is created.
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE child (id INT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE
);
Apologize if I didn't understand your question
UPDATED
INSERT table1 (col1, col2, col3)
SELECT col1, col2, col3
FROM table2
WHERE col1 = 'xyz'
Hope this helps
You don't need to store the user name in the events table. The point of the foreign key is that you only need to store the user ID in the events table, because that is a REFERENCE to the user.
To get the user name for an event, say event number 6, you would do
select name from users join events on users.id = events.u_id where events.id = 6
So, you should not be trying to insert user data into the events table. Just put the ID in there, and the user data will be available for you to retrieve using the foreign key.

New table or field with array in field (php/mysql)

I need to store multiple id's in either a field in the table or add another table to store the id's in.
Each member will basically have favourite articles. Each article has an id which is stored when the user clicks on a Add to favourites button.
My question is:
Do I create a field and in this field add the multiple id's or do I create a table to add those id's?
What is the best way to do this?
This is a many-to-many relationship, you need an additional table storing pairs of user_id and article_id (primary keys of user and article tables, respectively).
You should create a new table instead of having comma seperated values in a single column.
Keep your database normalized.
You create a separate table, this is how things work in a relational database. The other solution (comma separated list of ids in one column) will lead to an unmaintainable database. For example, what if you want to know how many times an article was favorited? You cannot write queries on a column like this.
Your table will need to store the user's id and the article's id - these refer to the primary keys of the corresponding tables. For querying, you can either use JOINs or nested SELECT queries.
As lafor already pointed out this is a many-to-many relationship and you'll end up with three tables: user, article, and favorite:
CREATE TABLE user(
id INT NOT NULL,
...
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE article (
id INT NOT NULL,
...
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE favorite (
userID INT NOT NULL,
articleID INT NOT NULL,
FOREIGN KEY (userID) REFERENCES user(id) ON DELETE CASCADE,
FOREIGN KEY (articleID) REFERENCES article(id) ON DELETE CASCADE,
PRIMARY KEY (userID, articleID)
) ENGINE=INNODB;
If you then want to select all user's favorite articles you use a JOIN:
SELECT * FROM favorite f JOIN article a ON f.articleID = a.id WHERE f.userID = ?
If you want to know why you should use this schema, I recommend reading about database normilization. With multiple IDs in a single field you would even violate the first normal form and thus land in a world of pain...

How to set a foreign key and retrieve or delete data from multiple tables?

I am new to php and mysql. I created a database named 'students' which contain two tables as 'student_details' which have fields like 'ID, Name, Age, Tel#, Address' and another table as 'fee_details' which have fields like 'ID(student_details table ID), Inst Id, Date, Receipt No'.
I want to set a foreign key and retrieve data from both tables when a student paid their fees and if a student passed out or discontinued I want a delete option to delete his all records from my tables. So please help me to solve this by PHP code and displays it in HTML while using a search form.
Enforcing referential integrity at the database level is the way to go. I believe when you said you wanted the delete "to delete his all records from my tables" you meant deleting the row and all its child records. You can do that by using foreign keys and ON DELETE CASCADE.
CREATE TABLE students
(
student_id INT NOT NULL,
name VARCHAR(30) NOT NULL,
PRIMARY KEY (student_id)
) ENGINE=INNODB;
CREATE TABLE fee_details
(
id INT,
date TIMESTAMP,
student_id INT,
FOREIGN KEY (student_id) REFERENCES students(student_id)
ON DELETE CASCADE
) ENGINE=INNODB;
With this, when a student is deleted from the students table, all its associated records will be deleted from fee_details.
you can try mysql_query() and mysql_assoc_array()

Categories