Reading information from two tables into two forms at once - php

For my first attempt at programming, I am making a simple webapp with php and MySQL, to enter customer information and store information about orders.
So far I've made a form to enter customer information, a page to edit that information and another page to show the different customers, which is all working fine.
I've run into a stump when trying to implement the next stage however.
I have an editcustomers page with 3 columns.
Column 1 shows a form containing customer information, allowing it to
be edited.
Column 2 allows ordering of products and showing how many products were ordered
Column 3 shows the total paid so far, and the total owing.
The code for the page I have at present:
<html>
<?php
$id = $_GET['id'];
require_once('connect.php');
$sth = $dbh->query("SELECT * FROM customers where id = '$id'");
$sth->setFetchMode(PDO::FETCH_ASSOC);
?>
<div id="main">
<div id="left">
<form name="myForm" action ="process.php" method ="post" >
<?php while($row = $sth->fetch()){ ?>
<p><input type = "hidden" name ="id" value="<?php echo $row["id"] ?>"/>
<p><input type = "text" name ="firstName" size ="30" value=" <?php echo $row["firstName"]?>"/>
<p><input type = "text" name ="lastName" size ="30" value="<?php echo $row["lastName"]?>"/>
<p></p>
<input type="submit" value="Update" />
<?php }?>
</div>
<div id="mid">
<p>Amount owed<br />
<input type = "text" name ="moneyOwed" size ="30" /></p>
<input type="submit" value="Pay" />
<p>Number of aaaa<br />
<input type = "text" name ="numAaa" size ="30" /></p>
<p>Number of bbbb<br />
<input type = "text" name ="numBbb" size ="30" /></p>
<p>
<input type="submit" value="Update" />
</div>
<div id="right">
<b>Total Balance</b>
<p> Money owed: </p>
<p> aaa total: </p>
<p> bbb total: </p>
<p> Total: </p>
<input type = "text" name ="pay" size ="20" /></p>
<input type="submit" value="Make Payment" />
</div>
<?php
$dbh =null;
?>
</body>
</html>
I have the following database structure:
A customers table, basic information like firstname, lastname, etc along with an id field.
A products table, listing the different products, only 1 row containing the costs for each product.
A purchases table, with an id field , fields like numProductA, numProductB, showing the quantity of each product ordered
The problem I'm having is that in my editcustomerspage, I have a database query to read in information from the customers table to fill the fields in the form in my first column and a separate query to update it if that if the function chosen.
Updating the second formshould be OK, as I could use a hidden field to differentiate forms, however I am unsure how to read the information in from the Customers table and from the Purchases table so that I can populate the fields in my second form..
Part of the problem is that the purchases table may be empty for a given customer, if that customer has not yet placed an order.
I was considering getting rid of the purchases table, and tacking the fields onto the users table which would solve my problem, although I think that is generally considered bad practice?
The products will be fixed in the application, and are not going to change. Even so, would it still be better to have column names cost and name and each products as a record?
What are some approaches I could take to solving this problem?

Even what you currently are doing is considered bad practice because of the columns numProductA, numProductB. What happens when you'll have 1000 products and a user orders different amounts from all of them. This work only if the list of products is fixed (i.e. coded into the application) and requires a lot of coding.
You would probably want to create a purchase_item table that has fields like: id, purchase_id, product_id, num_product. It would be like a line on a standard bill: purchase_id identifies which bill the line belongs to; product_id would show the product that line is about and num_product would show the amount (multiplier) on that line.
In this manner you don't need to change the code when new products are added to the database.

Without a detailed description of the problems you've run into, it's hard to say how to fix them. It should be possible to implement what you want with the described design. However, you seem to be misunderstanding relational databases, which is why your database architecture is eyebrow-raising.
A database table is not a spreadsheet. While a table can have millions of rows, the number of columns is usually limited to a much smaller number. Even when the limit is not a problem, the way relational databases are designed does not lend itself well to storage of uniform data across a large number of columns. For example, your database won't be able to answer questions such as “what's the best-selling product”, “what products have been purchased by more than 100 customers”, etc.
The rule of thumb is that each table should contain a fixed number of columns. If you find that you'll have to add columns when you e.g. start selling new products, you're doing it wrong.
Here's what you should probably do in your application:
products should be a table with one row per available product, containing, for each product, a unique id, the price and other information such as name, manufacturer etc.
purchases should contain one row for every combination of (customer, product) where a customer has ordered the product. The row shouuld contain the customer id, the product id, and quantity ordered.
Using SQL, you can then easily construct a query that produces the set of products ordered by a specific customer. Using a join, this information can be enhanced with product names and prices.

Related

Insert quantity of each types of item

I'm confused on how to actually let my form insert the data into the bag table that I have created. The system is supposed to store the bag of the customer where the bag_id is the customer id.
The number of rows generated for each customer in the bag table is dependent on the sizes of the bag they are storing.
The picture below is how I want the data to be inserted.
However, I can't figure out how to insert the data the way I wanted. This is what I try to do to get the number of each type of size:
<label>Bag Size</label></br>
<input type="text" name="big" id="big" class="form-control" style="width:5%;"/><label>Big</label>
<input type="text" name="medium" id="medium" class="form-control"style="width:5%;" /><label>Medium</label>
<input type="text" name="small" id="small" class="form-control"style="width:5%;" /><label>Small</label>
Any suggestion on the way to enter the data is appreciated.

Saving dynamic list items efficiently

I have supermarkets stored in my database. For each supermarket, in an admin area the user can create a shopping list with products and keep track of the products by checking (= user has already bought the product) or unchecking them (= user still needs to buy the product). My question is how to efficiently store the shopping list items in MySQL?
My markup with example data:
<form>
<h1>Supermarket: "City Store"</h1>
<p>Create/edit your shopping list:</p>
<ul id="shopping-list">
<li><input type="text">Tomatoes</input> <input type="checkbox"></li>
<li><input type="text">Apples</input> <input type="checkbox" checked="checked"></li>
<li><input type="text"></input> <input type="checkbox"></li>
</ul>
<button id="add-list-item">Add list item</button>
<button id="save-list-items">Save</button>
</form>
$('#add-list-item').on('click', function() {
$('#shopping-list').append('<li> <input type="text"></input><input type="checkbox"></li>');
});
In this scenario, when the user logs in, he sees that in the past he already added two products to the list, tomatoes and apples. As he already has bought apples, he had checked them. If he wants to add products, he can press the button.
In my MySQL environment I already have a table "supermarkets". For storing the shopping list items I want to create an additional table "shopping-list-items" with the following fields:
- id
- id_supermarket
- content
- status (1 = 'checked', 0 = 'still unchecked')
- date_created
- date_updated
- date_checked
As you can see, I want the date of each list item being saved, for when it is being created, updated AND checked.
How can I send the data of the shopping list to my database via POST and distinguish between checked and unchecked items? I basically know how to send data via the name attribute to a database and to save them, but in this case I want to save each entry individually and at the same time consider the checkbox state and I have no idea how to handle that.

Can't get my $_SESSION right

I hope someone can help me with some troubles I'm having. Currently I'm trying to make a simple webshop. First some information:
I have 2 kinds of products, product a and product b. Both of the products are available in 18 colours and 3 sizes. When you want to buy product a, you simply go to the page of product a, select your colour and your size, and then you add it to your basket.
The problem I'm having is that I can't manage to store the colour and size in the session as wel. Right now I'm storing the id of the product and the quantity in a session like this:
if (isset($_GET['add'])) {
$_SESSION['cart_'.(int)$_GET['add']]+='1';
}
The outcome of the session is: cart_1 1. It means that of the product with the ID 1, 1 has been added to the shopping basket. But what I want to do is that my session also can tell me which colour and size has been submitted. ($_POST['colour'] and $_POST['size']. The problem is that when I store it like this, I will only be able to order 1 of product a and 1 of product b because whenever I want to add another one of product a the 1 from cart_1 will be the same as the one with a different colour.
Thanks in advance!
Assuming that you got all options wrapped in a proper form then you can give each input an id.
Once you're on the current page which handles the form then you can easily access the inputs by referring to their ids.
Example:
<form id="mainForm" method="POST" action="scriptUrl.php">
<input type="text" id="color" value="" />
<input type="text" id="size" value="" />
<input type="submit" id="submitFormButton" value="Submit" />
</form>
Then you can easily access the values as such (once form submitted):
$color = isset($_GET['color']) ? $_GET['color'] : "";
$size = isset($_GET['size']) ? $_GET['size'] : "";
using the ternary operator.
And you can add this to your sessions if you want, it's preferred to have a single session for a single value, though. That is, if you feel that you really have to use sessions; there are other options, sometimes more suitable.
I know you're not using input texts but you can easily modify your example as such.
It differs between people whether they use GET or POST, I prefer POST.

Insert a customer borrowing a particular CD

So, I have question on whether the SQL statement for inserting a customer borrowing a particular CD is valid or not.
Here's the form I want the customer to fill out.
<form action="proj3.php" method="post">
<h4>Enter regular customer information.</h4>
Customer Name: <input type="text" name="cust_name"><br>
Customer SSN: <input type="text" name="cust_ssn"> (No spaces or special characters)<br>
Customer Telephone number: <input type="text" name="cust_tel"> (No spaces or special characters) <br>
<h4>Enter existing CD information.</h4>
CD Title: <input type="text" name="cd_title"><br>
CD Year: <input type="text" name="cd_year"><br>
<h4>Enter rent information.</h4>
Start CD Rent Date: <input type="text" name="rent_date"> (Format: YYYY-MM-DD)<br>
Rent Duration (days): <input type="text" name="rent_duration"><br>
<input type="submit" name="submit" value="Submit">
</form>
Here's the E-R diagram I did:
Now, the backend database stuff I'm definitely very new and a beginner to.
I want to insert a regular customer (non- VIP) that borrows/rents a particular CD. How do I write the SQL statement for that?
Essentially, I'm very confused on what table and attributes should the information go into? I have three tables that relate to this information. CD, rent and customer. What INSERT INTO statement am I writing?
I think it may have something to do with assigning IDs but I'm not sure how to do that yet. If there are any resources or tutorials I should read, please feel free to direct them to me. I'm stuck right now and just want someone to point in toward a certain direction on what steps to take or what to do from here?
EDIT:
Here's my attempt:
$sql= "INSERT INTO CD ( CD_title, CD_type, CD_year)
VALUES (‘$_POST[title1]’, ‘$_POST[type1]’, ‘$_POST[year1]’)");
But does that take care of the renting and customer aspect?
Try to read on basic SQL stements. Then try to come up with a solution on your own, and if you get stuck everyone here will be sure to help.
The way that I envision your system working is that you would have customer data in your customer table, cd information on every cd in your inventory in the CD table, and the rent table to be the cd's that are currently checked out. Is that how you have the tables set up?
If that is roughly how you have it setup, then I would write the query like this:
insert into rent(rentID, cdID, customerID,(and any other fields you have, comma separated))
values("(auto generated, or program generated rentID)","(cdID corresponding to the one being rented)","(customerID of the customer renting)","(Whatever else you're inserting)")
The idea is that each table will have a unique id (Primary Key) for each data item, such as an ID for each customer and an ID for each cd in inventory. You really wouldn't need much else in the rent table except the corresponding id's and any rental pertanent data, such as check out time, date item is due to be returned, etc. It is like a bridge connecting the other two tables. The other tables would hold any descriptive information, such as customer name, or year a CD was made, etc., and all be linked through the unique id's.
Hope my ramblings helped. :)

Duplicate form entries: How to send through to mysql database

I have a page where a user can create a recipe. I have a javascript script that allows the user to keep adding form input elements for more ingredients. Say the recipe has 4 ingredients the user can continue to add inputs. However this changes the id to ingredient1/2/3/4 for the input ID/Name,and i can't understand how to get around getting the information from the form post as the amount of elements is upto user discretion. How would you go about loading the results into PHP variables and then inserting them into a mysql query.
the syntax for the html form
<div id="ingredient1" class="clonedInput">
<h2 class="first-column">Ingredient</h2>
<span style="float:left; padding-right: 10px;">
<input type="text" name="scroll" value="Add Ingredient" id="ingredient" class="ingredient"/>
</span>
</div>
ingredient1 would change to ingredient2 for the purpose 2 ingredient's being added.
A slightly confusing problem, so any help would be amazing!
JB
I think what you are looking for is using [] in your input element names. This will post the data as an array. So, say you have this as your form's ingredient input elements (after javascript has added several):
<input type="text" name="ingredients[]" value="" />
<input type="text" name="ingredients[]" value="" />
<input type="text" name="ingredients[]" value="" />
<input type="text" name="ingredients[]" value="" />
<input type="text" name="ingredients[]" value="" />
When the user POST's the data, you will be able to access the array of ingredients at $_POST['ingredients']
I will tell you the logic, not the code as only javascript here would not be enough.
you create a table ingredients. Anything you can allow them to use. id, ecc
while posting, instead of doing giving the user a freedom chosing their ingredient1, ingredient2 ... you do load from ingredients table the values and index them as ingredient[id_from_db] ecc..
you create a table recipe. It should have a unique id, its description
you create a relation table recipe_id, ingredient_id
then when the user post its data you create 1 row in the recipe and as many rows in the relation table as the ingredients they use.
When selecting later the recipe you also select everything which is in the relation table, it could be several rows there...
Hope it is of any help for you. Can't show you any code for this, but it is not hard to make if you understand how it goes.
maxim

Categories