PHP echoing a specific field from a table in MySQL - php

Firstly, I'm quite new to PHP having only dived in some three weeks ago but loving it as a new thing to learn! I have a specific problem that I cannot seem to find a solution for via Google. I'm running a test page that will form the basis of a final product for a local recreational club that runs competitions and wants to display the results online on their website.
I've created a MySQL database and called it 'results' and imported as a CSV a sample of competition results. My code to connect to the database works as the page displays the "Database Connection Established" message.
The database contains a table called 'z_any_year_results' and the table structure looks like this:-
Record_Number Field Value
1 Field_1 Value_1
2 Field_2 Value_2
3 Field_3 Value_3
4 Field_4 Value_4
5 Field_5 Value_5
I understand how to select the specific table using
mysql_select_db("results") or die(mysql_error());
$data = mysql_query("SELECT z_any_year_results FROM results")
but I need to echo a specific field from the table in a specific section of the web page. So for example, in one section of the page I need to output the field containing the value Field_1 and nearby on the page the field containing the value Value_1. But in another section of the page I need to output the field with the value Field_4 and nearby on the page, the field containing the value Value_4. So I guess my problem is how to extract a specific piece of data from a table to the exclusion of all other records in the table and outout it as an echo on the web page. I cannot find anything on the web that is written in a simple step-by-stepway to help novices like myself understand.
Can anyone point me in the right direction on how to achieve this?
Many thanks in advance.

You are using a type of data design known as key/value design. In other words, each row has the name of a data item and its value. That's not an ideal sort of design for a beginner to use, because it makes for fairly intricate queries.
To answer your question, if you want a certain named field's value you use this query.
SELECT Value FROM z_any_year_results WHERE Name = 'Field4'
But, maybe you want a design that resembles your application's entities a little more closely.
You might have an entity, a table, called, contestant, another called contest, and another called prize.
contestant is a table with columns like contestant_id, surname, givenname, email etc
e.g. 1 , Ellison, Larry, larry#oracle.com
Then you can use queries like SELECT * FROM contest WHERE YEAR(datestart) = 2016 which will make your queries more closely reflect the logic of your application.

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.

Create A List From a Category Section in mysql

I was wondering if mysql has a way to look at a column and only retrieve the results when it finds a unique column once. For example
if the table looks like this:
id name category
1 test Health
2 carl Health
3 bob Oscar
4 joe Technology
As you can see their are two rows that could have the same category. Is their a way to retrieve the result where the array will one only return the category once?
What I am trying to do is get all the categories in the database so I can loop through them later in the code and use them. For example if I wanted to created a menu, I would want the menu to list all the categories in the menu.
I know I can run
SELECT categories FROM dbname
but this returns duplicate rows where I only need the cateogry to return once. Is there a way to do this on the mysql side?
I assume I can just use php's array_unique();
but I feel like this adds more overhead, is this not something MYSQL can do on the backend?
group by worked perfectly #Fred-ii- please submit this as answer so I can get that approved for you. – DEVPROCB
As requested by the OP:
You can use GROUP BY col_of_choice in order to avoid duplicates be shown in the queried results.
Reference:
https://dev.mysql.com/doc/refman/5.5/en/group-by-handling.html
By using database normalization, you would create another table with an unique id and the category name and by that link those two together, like
select * from mytable1
on mytable1.cat = mytable2.id
group by mytable1.cat
You can ofcourse also use group by without multiple tables, but for the structure, I recommend doing it.
You can use select distinct:
SELECT DISTINCT categories
FROM dbname ;
For various reasons, it is a good idea to have a separate reference table with one row per category. This helps in many ways:
Ensures that the category names are consistent ("Technology" versus "tech" for instance).
Gives a nice list of categories that are available.
Ensures that a category sticks around, even if no names currently reference it.
Allows for additional information about categories, such as the first time it appears, or a longer description.
This is recommended. However, if you still want to leave the category in place as it is, I would recommend an index on dbname(categories). The query should take advantage of the index.
SELECT id, name from dbname GROUP BY categoryname
Hope this will help.
You can even use distinct category.

Updating multiple rows with an array

I have a table that holds user information. One of the columns holds the position of the user in the game they are in.
When a game is being created, I need to update the positions of the users of each team.
Here is an example:
Game id : 7
Team 1 users : 1,2
Team 2 users : 3,4
team1_position : array(1,2)
team2_position : array(13,14)
What I want to do is update the user table using the array of positions in the SET area.
My goal is to be able to update the users without the need for their id (I have different size game boards, so I have multiple position arrays for each board size)
How can I do something like this:
UPDATE user
SET position='(team1_position)'
WHERE game = '7' AND team = '1'
I feel like it would be a waste of resources to select all the id's of each team and update them separately.
I have a hard time understanding what you are trying to do, better explanation would be nice. From what I understand you are selecting data from tables in order to update other tables. Have you tried using an "UPDATE .. JOIN .." query? This should allow you to update multiple rows from one table based on associative data from another table.
For example
UPDATE user
JOIN game ON
user.id=game.id_user
SET user.position=game.team1_position
Obviously this wont work with your code as I have very little info to go on, but that should give you an idea of what to go with.
Sorry if I'm totally off in understanding your problem, as said it's a bit hard to understand your exact issue based on what you've given us.

User Reviews: Implementation of Comments - What technologies to use?

I have set up a company intranet website built with PHP/MySQL and allow users to post reviews. After joining up on this website I have grown to like the "comment" function and would like to add that same functionality to allow users to "comment" directly to other users reviews.
Currently all reviews are stored in a single table in the DB.
1) Should I create another table to then store all the comments since there can be many comments per review?
2) Once I figure out where to store these values can the rest of this functionality be built out in PHP or will other programming need to also be introduced?
Sounds like a good plan. You can have a table like Comments(commentID, reviewID, comment_body, ...). You can then insert a new entry when adding a new comment, or select all comments with a given reviewID to display comments for a given review.
Yes, you will almost certainly implement this in PHP (the same language you use in the rest of your application). You'll also have to edit some HTML, and maybe javascript as well.
Yes and yes.
Comments should be a seperate table, because they're comments, not reviews. They are two different things, therefore, they should not go in the same table.
Once you've created that table with the appropriate references to other tables, it's just a matter of constructing a query which pulls out all of the information you need (e.g. SELECT user.user_name, comment.comment_text, comment.post_time FROM comment, user WHERE comment.user_id=user.user_id AND comment.review_id = 123, where 123 is the ID of the review you're getting comments for).
The exact layout for your comment table will depend on your specific needs, but as a minimum, you'll want to know which review it's a comment for, who posted it, when they posted it, and what they actually posted.
To insert comments, create a form on the page that displays the individual review, and when filled in, create an INSERT query which inserts into your comment table.

Store dynamic form fields in database

I have read other answers on this (or at least near to this) subject but I couldn't get a clear view of it so I'm asking for help again.
I have a complex dynamic HTML form that I would like to submit to database using PHP. The form is split into multiple tabs and in each tab I got checkboxes that trigger other parts of the form. Example: at a point in my form I got a checkbox group that has options of: "hotel" and "restaurant". If I check hotels, I get another part of the form displayed, specific for "hotels". Same thing for "restaurant". So it's very dynamic here and I don't know which would be the best approach for storing every form field in database. Because it could contain 15 fields or 20, depending on the selection. Any example would be appreciated as I'm not that advanced with database design.
Thank you!
So it's very dynamic here and I don't
know which would be the best approach
for storing every form field in
database.
I apologise if I have misunderstood you here but I believe that you should design the database according to the data and not the form. It is difficult to comment without knowing the exact details of your situation so here is an example:
If you usually dump all the data from a form into a single table, but because sometimes this will involve submitting 5 values and other times this will involve submitting 10 and so you are unsure how many columns your table should have, then I think the problem is in the database design.
Work out what pieces of data are dependent on other pieces of data. For example, you mention checking "hotel" might open up more fields specific to that choice. Let's assume this involves things like "en-suite", "bed type" etc. Then you should have 3 tables, a registration table (assuming the user is using the form to buy these services), a hotel table and a registration_hotel table. The registration table will record a number of details specific to the registration only such as the customer's name and a unique id number. The hotel table will hold information specific to the hotel only, such as how many rooms have en-suite. The registration_hotel table will hold details specific to that registration at that hotel. You might want a column of type bool to record whether the user requested "en-suite".
When submitting the form, check which pieces the user entered with if(isset($_POST['hotel']) && !empty($_POST['hotel'])). Then only send stuff to the registration_hotel table if that condition is true.
If this design results in making too many separate calls to the database, you might want to look into transactions which will help you to manage the speed and security of these calls.
If you can post in a specific example of something you don't know how to do, that would be useful.
You didn't specify how you can manage this dynamic form. Can you edit it's PHP/HTML source? One great thing would be if you can label your different variables like hotel[], restaurant[], etc.
If your submitted form is clear enough (i mean semantically correctly structured) you can store the whole submitted form serialized.
Note: this method only working when you don't need to search for specific items in your database.
Edit: maybe i'm misunderstood your problem.
You can create a 'metadata' table like this:
form_id | option_name | option_value
---------------------------------------
1 | hotel | true
1 | restaurant | false

Categories