SQL database issue - php

I have a select statement showing the following results:
On_loan barcode
Y 12345
Y 12345
N 12345
N 12344
Y 12344
Each barcode for a book can have more than one copy. Users can place a book on hold. E.g user '1' has reserved book 12345 and 12344. The above results show: that the two books with barcode 12344- one is available, the other is unavailable. I want to be able to show two regions in PHP, the top showing books that are ready to take out(that were on hold) and the other showing books that are unavailable which have been placed on hold. From my select query i now want my select to check to see for each barcode 12345 and 12344 whether a book has been returned. If it has i will then use the hold_date to see if its the earliest Hold for the specific book.
I understand on_loan informs me whether a book has been returned, however how can i use 'N' from on_loan for each book. I believe distinct will not work.
How can i go about doing this.
My Hold table
has the following fields:
user
isbn
hold_date

I think you are asking for a way to check if a recently returned book is on hold for another customer, correct?
The book should actually have a unique barcode per each physical copy of a book in the library, as well as an ISBN for the book in general.
Holds would be placed by ISBN.
When a book is checked in, enter that copies barcode, then pull its ISBN number and see if another customer is waiting for it.
If so, set the status for that copy to 'hold', create a related library book to hold record relation.
Otherwise, set the book status to checked in.
Assuming there is a table 'copy' that has a record for each physical copy with unique barcode and relates to a table called 'book'
that has info about a book like ISBN and Author etc, and a table called 'hold' that has the hold info an ISBN (or better, book.id)
Here are the all the copies that are checked in and have a hold on them.
select * from copy left join book on book.id = copy.book_id where copy.status_id = get_book_status('in') and book.isbn in (select isbn from hold);

Maybe you should have a bookTitle table with ID, Barcode, link to barcode tables and then you could do a query to return all copies of a bookTitle and use queries to return barcodes that are on loan and not.
The ID makes it unique.

That's not quite a good database design, if you are asking this kind of questions.
First of all, you should transform this to the third normal form databse.
Then it will look like three tables: books (name, barcode, available_count), users(user_id, name) and a relationship table users_to_books(user_id, book_barcode, state), where state can be an menu with values "on hold" and "on hands".
After that you can do all kind of stuff with counting and checking.

Related

PHP echoing a specific field from a table in MySQL

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.

mySQL Database - Storing Multi-Criteria Ratings

I've been doing a lot of searching and reading about rating systems, but couldn't find a solution to what I'm trying to achieve...
I have a website where users, once logged in, can submit a product. Now I want other users to be able to rate those products according to 3 different criteria. I'm using php and mySQL databases to store all of the information which is working great, I'm just not sure how to incorporate the ratings now.
At the moment I have a PRODUCTS database, which holds various tables according to their category. Here's an example of a table:
TOASTERS
---
ID (auto-incrementing)
Brand
Set
Number
Name
Edition
Image (stores the location of the image the user uploads)
Any user can then rate that row of the table out of 10 for 3 criteria (Quality, Price, Aesthetic). The user average of each criteria is displayed on each product page but I would like to store each of the user's individual ratings so that I can show a short history of their ratings on their profile page. Or have a live feed of the latest user ratings on the homepage.
What I'm trying to do is quite a lot like awwwwards.com. (See bottom-right of page to see the livefeed I'm talking about)
Thanks in advance!
I think you should use single PRODUCTS table or at least create PRODUCTS table and emulate inheritance between it and category tables.
Having a table for each category can give some advantages if each category has some specific properties, but it can lead to neccesity of writing separate code to work with each table. Alternatively you can use two tables to store all custom properties 'vertically': PROPERTIES(propertyID,PropertyName), PROPVALUES(productID,propertyID,PropertyValue).
If you choose to have multiple tables and emulate inheritance, it can be achieved like this:
PRODUCTS
---
ID (auto-incrementing)
Brand
Set
Number
Name
Edition
Image
VoteCount <+
SumQuality +-updated by trigger
SumPrice |
SumAesthetic <+
TOASTERS
---
productID (PK and FK to PRODUCTS)
(toaster specific fields go here, if any)
Than you will be able to create table VOTES, referencing table PRODUCTS
VOTES
---
productID (FK to PRODUCTS)
userID (FK to USERS)
Quality
Price
Aesthetic
VoteDateTime
If it is true that overall product rating is queried much more often than voting history, as an optimization you can add fields VoteCount, AvgQuality, AvgPrice, AvgAesthetic to PRODUCTS table, as srdjans already supposed. You can update this extra fields by trigger on table VOTES or manually in PHP code.
Create separate table for storing user individual ratings (primary key, user id, product id and ratings). Create additional fields in "products" to store averages. Every time some user rates some product, you insert record in "ratings" table, then calculate averages again for given product, and update rows in products. Doing this you will have easy access to ratings, and also, you can analyse user individual ratings.
Ps - You may also wish to store how many users rated some product.

How to design a database to keep track of books my family owns?

I am not necessarily looking for MySQL or PHP code. Rather I'm trying to get a concept of how to set everything up.
I want to create a database using MySQL (and using PHP to update it) of all the books my family owns. I want to set up different 'bookshelves' for each person in my family so we can see who has a certain book.
My first thought was to have a table for all the titles, authors, etc and have a field for user id to show who had the book. However, I might have a copy of Hunger Games and my grandmother might have a copy of Hunger Games. I want to be able to show it on both bookshelves. The only way my idea would work is if we had no duplicate books.
My next idea was to use a different table for each user and have a field that contains the book id for each book the user owns. I think this would work on a small scale but it does not seem like an efficient design. I am planning on making the database public for everyone in my town to use (thousands of people) once I get a stable website going so I want to start off with the right kind of design.
How should this be designed?
BOOK
--------
book_id
title
other_book_related_info
PERSON
-------
person_id
name
other_person_info
BOOK_PERSON
-------------
book_id
person_id
possibly-dates-when-this-person-owned-this-book
Here is one simple solution i can think of:
Book Table : List of all unique books
User Books : contains the user id and the book id. multiple users can own the same title.
Users : List of users;
This is pretty basic. Owner, book and author should be self explanatory. Add any additional fields to those tables you want. The bookshelf and book_authors are both cross reference tables so each book can have multiple owners and each book can have multiple authors.
**owner:**
owner_id
owner_name
...
**book:**
book_id
book_name
...
**author:**
author_id
author_name
...
**bookshelf:**
owner_id
book_id
**book_authors:**
book_id
author_id
You might like to differentiate between ownership of the book and current possession, since people will doubtless be borrowing. So the tables of BOOK (best call it ITEM if you're going to expand to DVD's etc) and PERSON, and the ownership table BOOK/MEDIA_OWNER, might be usefully accompanied by an ITEM_LOAN table.
You might like to also allow grouping of sets of items so that multiple volumes of a book, or discs of a show season, can be identified individually. Books (and films etc) also come in series, so think about how to represent that as well.
By the way, it's a generally accepted rule that if an edition of a work changes by more than 20% between print runs then it is a new impression, but it is not always granted a new ISBN. Depends on the publisher. Also, the hierarchy for books is based on Work -< Edition -< Impression, and these folks would be a good source of information of data structures relating to books.
Here's another solution:
**** BOOK ***
book_id
book_title
book_desc
book_bought
*** USERS ***
user_id,
name,
dateOfBirth
** Copies **
copy_id (PK)
user_id (FK)
book_id (FK)
NoOfCopies

Insert Registration Data in MySQL using PHP

I may not be asking this in the best way possible but i will try my hardest. Thank you ahead of time for your help:
I am creating an enrollment website which allows an individual OR manager to enroll for medical testing services for professional athletes. I will NOT be using the site as a query DB which anybody can view information stored within the database. The information is instead simply stored, and passed along in a CSV format to our network provider so they can use as needed after the fact. There are two possible scenarios:
Scenario 1 - Individual Enrollment
If an individual athlete chooses to enroll him/herself, they enter their personal information, submit their payment information (credit/bank account) for processing, and their information is stored in an online database as Athlete1.
Scenario 2 - Manager Enrollment
If a manager chooses to enroll several athletes he manages/ promotes for, he enters his personal information, then enters the personal information for each athlete he wishes to pay for (name, address, ssn, dob, etc), then submits payment information for ALL athletes he is enrolling. This number can range from 1 single athlete, up to 20 athletes per single enrollment (he can return and complete a follow up enrollment for additional athletes).
Initially, I was building the database to house ALL information regardless of enrollment type in a single table which housed over 400 columns (think 20 athletes with over 10 fields per athlete such as name, dob, ssn, etc).
Now that I think about it more, I believe create multiple tables (manager(s), athlete(s)) may be a better idea here but still not quite sure how to go about it for the following very important reasons:
Issue 1
If I list the manager as the parent table, I am afraid the individual enrolling athlete will not show up in the primary table and will not be included in the overall registration file which needs to be sent on to the network providers.
Issue 2
All athletes being enrolled by a manager are being stored in SESSION as F1FirstName, F2FirstName where F1 and F2 relate to the id of the fighter. I am not sure technically speaking how to store multiple pieces of information within the same table under separate rows using PHP. For example, all athleteswill have a first name. The very basic theory of what i am trying to do is:
If number_of_athletes >1,
store F1FirstName in row 1, column 1 of Table "Athletes";
store F1LastName in row 1, column 2 of Table "Athletes";
store F2FirstName in row 2, column 1 of Table "Athletes";
store F2LastName in row 2, column 2 of table "Athletes";
Does this make sense? I know this question is very long and probably difficult so i appreciate the guidance.
You should create two tables: managers and athletes
The athletes table would contain a column named manager_id which would contain the id of the manager who signed the athlete up or NULL if the athlete signed himself up.
During output, create two CSV files (one for each table).
Further reading:
Defining Relationships
If you will retain the names for a future submission, then you should use a different design. You should also consider if a manager can also be an athlete. With those points in mind, consider having three tables: PEOPLE, REGISTRATION and REGISTRATION_ATHLETE. PEOPLE contains all athletes and manager. REGISTRATION is the Master table that has all the information for a submission of one or more individuals for testing. REGISTRATION_ATHLETE has one row for every Athlete to be tested.
People table:
---------------
People_ID
Type (A for Athlete, M for Manager B for Both)
First Name
Last Name
Birthdate
other columns of value
Registration table:
-------------------
Registration_ID
Registration_Date
People_ID (person requesting registration - Foreign Key to PEOPLE)
Payment columns....
Registration_Athlete table:
---------------------------
Registration_ID (Foreign Key to REGISTRATION)
People_ID (Foreign Key to PEOPLE)
I am not a mysql person, but I would think this simple type of structure would work.
Finally, storing credit card information is problematic as it runs into PCI (Payment Card Institute) rules, which you will want to avoid (think complicated and expensive). Consider processing payments through a third party, such as Google Checkout, etc. and not capturing the credit card.
Well based on your comment reply and what you are looking for. You could do this.
Create one database for Registration.
Create the columns ID, name, regDate, isManager, ManagerID (Whatever Else you need).
When a Manager enrolls set isManager to 1 and form a hash based on name and regdate, that would be the Managers Unique ID that would be added to all of the Athletes entries that the manager registers.
When a lone athlete registers don't worry about the ID and just set isManager to 0.
I think I may be oversimplifying it though. Wouldn't be the greatest for forming different types of queries but it should be alright if you are trying to minimize your db footprint

Display rows based on $array

I have a table in postgres called workorders. In it are various headings. The ones I am interested in are labor, date_out and ident. This table ties up with wo_parts (workorder parts). In this table are the headings I am interested in, part and workorder. Both are integers. (part auto number) The final table is part2vendor and the headings are retail and cost. Right, basically what happens is.....I create a workorder (invoice). This calls a part from part2vendor. I enter it and invoice it off. In workorder a row is created and saved. It is given an ident. In wo_parts, the part i used is recorded as well as workorder number and qty used. What I want to do is create a report in php that pools all this info on one page. IE. if i choose dates 2009-10-01 to 2009-10-31 it will pull all workorders in this range and tell me the total labour sold and then the PROFIT (retail less cost) of the parts I sold, using these 3 tables. I hope i have explained as clear as possible. any questions please ask me. Thank you very much for your time.
You will want to read up on SQL - keywords to look for include "aggregate", "SUM" and "GROUP BY".
You query will look something like (but this will certainly need correcting):
SELECT
SUM(wo.labor) AS tot_labor,
SUM(p2v.cost - p2v.retail) AS tot_profit
FROM
workorders AS wo
JOIN wo_parts AS wp ON wo.ident=wp.ident [?]
JOIN part2vendor AS p2v ON ...something...
WHERE
date_out BETWEEN '2009-10-01'::date AND '2009-10-31'::date;

Categories