Mysql/sql/zend query with one select? [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Well so I got a tiny problem, I got a db and 2 tables like this
Table User
user_id
Table UserrToData
user_id int pk
data_id int
Table UserData
data_id
name
nick
I got the user_id and i need to get records from the userdata , is it possible using 1 query?
Of course, if anyone know how I would really appreciate if he would help me : )
For the selecting I got only the relationship user_id > data_id
update
Guys I got huge db I just simplified the problem to the minimum ^_-

Hope this helps:
SELECT name, nick
FROM UserToData utd INNER JOIN UserData ud ON utd.data_id = ud.data_id
WHERE utd.user_id = [supplied userid]
With such little data, however, there is no need for separate tables, just store name and nick in the User table:
Table User
user_id pk
name
nick

You should overthink your database design. The highest aim is always to prevent redundancies.
If you want the user to have more than one userdata entry you should define your database like this:
Table User
user_id pk
Table UserData
data_id pk
user_id fk
name
nick
So the query would be SELECT * FROM UserData WHERE user_id = ?.
If you only want the user to have one set of userdata you should integrate it into the user table:
Table User
user_id pk
name
nick
So the query would be SELECT * FROM User WHERE user_id = ?.

Why have you put the name and nick in a separate table? You can just put the data in one user table. Might be wise to learn more about how to formulate entities and relations in your database.
Either way, if you ever need to do something like this in Zend at a later time, you can use Zend_Db_Select and do a join. Lookie lookie: http://framework.zend.com/manual/1.12/en/zend.db.select.html#zend.db.select.building.join

Related

Save statistics of wrong questions answers to database

I'm making a quiz game, and I want to make statistics of questions that has been answered wrong.
I have a database with 3 tables: Questions (all questions), Answers (the alternatives for each question), Games (stats about each game sessions).
Right now I'm thinking of two alternative ways to make a solution for this.
Save each question ID into an array, then save the array
into one record in MySQL at the end of the game.
Insert a new record with question ID into the table for each wrong
answer.
Which of these options would be the best approach to solve my problem? If I'm correctly, the last one will be easier when I'm gonna query the database to show questions that has been answered wrong. Any input or suggestions would be appreciated!
My advice is to save each answer given into a separate row, exactly for the reason you stated. Querying such a structure will be much easier than having multiple answers stored in a single row.
I would structure the tables as follows
Question
ID | Text | whatever else you may need
Answer
ID | QuestionID | Text | IsCorrect | whatever else you may need
Game
ID | User | StartTime | EndTime | whatever else you may need
Stats
ID | GameID | QuestionID | AnswerID | AnswerTime | whatever else you may need
This would need adjustments depending on the kind of analysis you're planning to do on it, but you get the idea.
Counting the number of times a wrong answers has been given would be as easy as
select t1.ID, count(*)
from Answer t1
join Stats t2
on t1.ID = t2.AnswerID
where t1.IsCorrect = 'N'
group by t1.ID
I am not sure I understood correctly your question. What follow is a possible solution for table statistics for answers if you want detailed information for each question / answer :
CREATE TABLE GAME_STATS (ID INT NOT NULL, ID_QUEST INT, ID_ANSWER INT, NUM INT);
ID is a sequence (you could omit this and make PK ID_QUEST, ID_ANSWER)
ID_QUEST refers to ID of table Questions
ID_ANSWER refers to ID of table Answers.
NUM is the number of times that answer has been selected.
You could consider to prepopulate the table for all possibile questions / answers (NUM = 0).
At the end of every answer, you should update the NUM (+1) for ID_QUEST, ID_ANSWERS.
If you want register statistics for each session / user, you should add appropriate columns (ex. id_session, and/or user_id).
In this case you can't prepopulate table. And you can register only wrong answers.

Show data from database based on user input

I'm creating a way that a "teacher" could make an exam and the "student" can take an exam.
First off, it is also possible for a teacher to make new questions, using this query:
INSERT INTO questions (question, type) VALUES ('$question', '$type')
In the database, I set questions to also have question_id which is auto incremented after each entry. Then on a separate page, they can pick which questions they would like to add to the exam. So I just:
SELECT * FROM questions
Then there is a checkbox for them to check which questions to add the use this query:
INSERT INTO exams (question_id) VALUES ('$question_id')
The table exams also has an auto incremented exam_id.
So now I would like to display the questions the teacher picked, but I don't even know what type I should store question_id in exams (right now it is INT) so I can loop through them.
ie. Teacher picks questions 1,2,4,10 and query for getting the question would look like
SELECT question FROM questions WHERE question_id='1,2,4,10'
Assuming you are getting the question id by POST or GET, Try this:
$selected = implode(',', $_REQUEST['selectedquestionids']);
SELECT question FROM questions
WHERE question_id IN ($selected)
GROUP BY question_id;
Hope this may help.

Create timeline from data in different tables [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a few tables in my script that I need to create a timeline from all of them. The main tables are "posts" - "likes" - "comments".
posts table has rows: PID - UID - title - time_added.
likes table has rows: LID - PID - UID - time_added.
comments table has rows: CID - PID - UID - time_added.
users table has rows: UID - username.
I'm creating a page in the users' profiles called: "Timeline". It should show the actions of the user sorted by time. UID refers to the user ID.
Data example while browsing that page:
User Commented on Post xxxx at xxx_time_added_xxx.
User Liked post xxxx at xxx_time_added_xxx.
User added Post xxxx at xxx_time_added_xxx.
Is there's a way or MySQL query that can combine all these tables and arrange them by time_added?
I thought of creating a new MySQL table: user_timeline that has rows:
TID - UID - PID - LID - CID
And after each action (Post, Like, Comment) and new row is inserted in that table according to the action and add the action ID in the corresponding field and leave the others null. Then call them combined with the related table, if possible.
you can with UNION and aliasing:
select * from ((select 1 as type,time_added from posts where ...) union (select 2 as type,time_added from likes where ...) ...) order by time_added asc
NOTE: Column selection must have the same order in regards to the column type.
Do not do:
(select 1 as type,time_added from posts where ...) union (select time_added,2 as type from likes where ...)
Or if you don`t select the same number of columns in subqueries:
SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns
Your result set will be an multi dimensional array as follows:
array(array('type'=>1,'time_added'=>'...'),array('type'=>2,'time_added'=>'...'));
By TYPE you know if it is a post or a like
Hope this helps

Storing more than one string in a MySQL Database Table

Before I ask my question, I just wanted to thank everyone that replied to my question yesterday -> Countdown using javascript.
Idea:
I created a quiz using php, but I would like to create a MySQL Database and having a table with all the questions, answers and multiple choice stored inside.
Issue:
Since the quiz is multiple choice, I don't know how to go about storing the multiple choice options in the table. Could I store the options and have each answer separated by a special character and let php get the string and separate the options?
Ex: Question: What is your favorite color? Options: Blue=Red=Purple=Yellow.(Database View)
What do you folks think is the best practice for something like this?
I think the best practice would be to use multiple tables. One for the question and one for answers. The answer table would contain question_id as well as a flag whether or not it is the correct answer
It could look like this
TABLE questions
FIELDS: id, text
TABLE answers
FIELDS: id, question_id, text, correct
The problem with using one field for all the answers is that you could accidently use the character you use for splitting inside the text of an answer
simply, create two tables:
questions
question_id, question
answers
answer_id, question_id, answer
Now, you can link these two tables using question_id
There are a couple of ways around this :
The "proper" way is to create another table ( so that you have a table called "questions", each of which have a unique id, and another called "answers", where each has the question id )
The "simple" way, which is to use JSON ( see json_encode and json_decode ) which takes care of using special characters etc in a field
You'd have a questions table, like this:
id | question
0 Do you even lift?
id would be INT(11) PRIMARY_KEY AUTO_INCREMENT while question would just be TEXT. Then, you would have an answers table:
id | question_id | answer
0 0 Yes
1 0 No
2 0 Maybe
Here, question_id refers to the ID of the question in the questions table. These answers all belong to one question. This is called a Has many relationship, as one question has many answers.
This is how its usually done. Implementing it is not that hard, even if you're not using a framework (most of them do the work for you).
Hope this helps
Tables:
quiz
quiz id (pk)
quiz info (other columns)
questions
question id(pk)
quiz id
question text
answers
answer id(pk)
question id
answer text
To display a given question do a join on the quiz, question and answers.
EDIT: You could either add a column for 'right/wrong answer (0/1)' or have another table:
solutions
solution id(pk)
question id
answer id
I didn't put the 'correct answer' in the answers table as that's not good normalization.
There could be many possible schema designs for this but my suggestion is like this:
Don't ever store values separated by comma on the tables.
This table holds the quizzes.
Quiz Table
QuizID (PK)
other columns..
This holds the questions for every quiz.
Question Table
QuestionID (PK)
QuestionDetail
QuizID (FK)
other columns...
This holds the answers.
Answer Table
AnswerID (PK)
AnswerDetail
This holds the correct answer for every question on each quiz or in other words, this is the answer key.
Question_Answer_Correct Table
QuestionID (FK) -- also a compound primary key with AnswerID
AnswerID (FK)
This contains list of users.
User Table
UserID (PK)
UserName
other columns...
This contains answer of users on a specified question. There is no QuizID here since the questions are already connected on the quiz table.
User_Answers Table
UserID (FK)
QuestionID (FK)
AnswerID (FK)

Quiz - user submissions into MySQL database

What I am trying to achieve: a quiz system with user account and cumulative results table.
Process:
-User sets up an account
-User logs in
-User completes quiz
-Answers go into results table
-Results table displayed
My database structure:
Table 1: users
user_id
username
password
email
Table 2: quizzes
quiz_id
title
Table 3: questions
question_id
quiz_id
question
question_notes
Table 4: answers
answer_id
question_id
user_id
answer
answer_notes
Table 5: responses
response_id
quiz_id
user_id
submit_time
The questions will be output from Table 3 via a SELECT.
What I am looking for some pointers for is how I can ensure the relationships for each quiz entry is consistent, so when I run the INSERT statements the IDs are consistent (so the "question_id" for Table 3 and Table 4 are the same, for example)
I am thinking I will have 2 INSERT statements for Table 4 and Table 5. In these insert statements, is there a way to ensure the relationships match?
I am having some trouble visualising how this will work for entering the data into the database, once I've got this figured out I can tackle using the data.
Any pointers to decent tuts or a bit of insight into possible form processing would be much appreciated.
Many Thanks
There's LAST_INSERT_ID() function in MySQL ( mysql_insert_id() in PHP ) that will return auto_increment id from last insert query. This will let you keep consistency.
See here for more details:
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
Foreign keys and transactions enforce referential integrity...
For example:
Answers
question_id is a foreign key to question.id
user_id is a foreign key to user.id
(These are set in the table definition)
You insert in to answers like so (sloppy pseudocode):
begin transaction
int qid = select id from question
int uid = select id from user
insert (qid,uid,...) into answers
commit transaction

Categories