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.
Related
I have a html form with about 280 text, radios and select dropdown fields. I have to capture a lot of information about people's outgoings. Eg. Who their gas and electricity providers are, how much they pay, the rates, their bank accounts, loan accounts, broadband etc. The list of fields sounds huge, but it's laid out in tabs and it isn't too overwhelming and people don't have to fill in all of it anyway.
I present the blank form to the new user and then post every field value (blank or not) to the mysql dbase on the first submit.
The problem is.. how do I retrieve all that data and put it into the form the next time? I'm out of my depth with elegant solutions, so I guess I'd do a foreach loop through each database record retrieved and save it to a variable, but then I have to insert the 280 field values into the fields using an statement in the value="xxx" for each field, something like:
<div class="form-group row">
<label for="loan1name" class="col-lg-5 control-label text-right">Loan Name</label>
<div class="col-lg-3">
<input type="text" class="form-control" name="loan1name" placeholder="Car loan" value=<?php echo htmlspecialchars($loan1name) ?>>
</div>
</div>
If I had 10 fields it wouldn't matter, but 280 is unmanageable doing it that way. Is there any other way? Do I need to go about this a completely different way? Does it make sense to duplicate the form and use one for the blank one which does the INSERT, then another for the pre-populated version for the UPDATE query? Any help would be greatly appreciated. I just know there must be a better way, but I can't find any answer on here or anywhere else.
It doesn't seem simple because the fields are quite varied and one is even a set of pictures as a radio button sequence (it's pictures of types of locks you have on your front door - for your home insurance).
Mysql usually return an associative array. You can then use the key/value pairs in this array to dynamically create your form.
<?php foreach($fields AS $name => $value){ ?>
<input type="text" name="<?= $name ?>" value="<?= $value ?>" /><br />
<?php } ?>
Note: The downside is that you are still missing the label and placeholder of each input. Also, they would all be text input.
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.
I'm doing a flight booking site with PHP for my assignment. The search page returns a table of related flight details from the key word that was entered. Then in the table it gives the option to choose only one flight to book. After selecting a certain flight by radio button and clicking "make booking for selected flight" button, the next page is required to display the flight details that have been selected from the previous page.
The problem is: how do I display the selected flight details?
I'm sure you did use the form for user to selected the appropriate options. Let's say:
<form action="nextpage.php" method="post">
<input type="radio" name="flight" value="flight1" />Option 1<br />
<input type="radio" name="flight" value="flight2" />Option 2<br />
......
<input type="submit" name="booking" value="Make Booking for the Selected Flight" />
</form>
Then on page nextpage.php you can get the flight that user have selected by using the php code below:
<?php
$flight = $_POST['flight'];
//do things u need here, for example
echo $flight;
?>
Pass some unique identifier from your flight to the details page via URL variable. To access those variables, simply use the PHP $_GET['id'] variable (in this case to access a url variable named id).
To pass an "id" url variable, simply append ?id=value to your redirect: http://page.com/details.php?id=5
Once you have this on your second page, it is very easy to do another MySQL query to retrieve the details from flight, say, 5 and display it on the second page.
You can use following method to send data on next page.
1) Session
2) Cookies
3) Get method
4) Post method(Using hidden fields).
There are number of records which I gather them from mysql say thease:
id name mark
1234 john 18
53 smith 12
324 mike 15
...
I want to build a form to give ability to edit(update) all marks at once
I know that I can show them at the form using textbox value property.
But how can I Identify the exact same record when I want to process the posted form, in order to update the correct filed? and surly, I don't know how many records are there in the form.
The idea might be identifying the records through the id field.
but how to do that?
If this application is for administrative use only:
<input type="hidden" name="id" id="id" value="_ID_VALUE_" />
<input type="text" name="name" id="name" value="_NAME_VALUE_" />
<input type="text" name="mark" id="mark" value="_MARK_VALUE_" />
then
UPDATE table SET mark = '_SANITIZED_MARK_VALUE_' WHERE id = "_SANITIZED_ID_VALUE_";
If it's an application for the end user, you don't want to trust that he/she won't change the value of the hidden input. In this case, you'll most likely want to store the id, name, and mark in a $_SESSION variable and do comparisons on the post to figure out which record pertains to which id, and then build your update statement accordingly.
When you build your form, use the ID from the database as part of each text field's NAME attribute. Then when you receive your array of posted values, you can process the keys to find out the ID of the record you should be updating. For example, you could have your fields named "record-1234", "record-53", etc. Then you would iterate over the keys in $_POST, split them on "-" and use the resulting IDs in your UPDATE query.
I have a long questionnaire (46 questions) with each having (3) possible answers, yes, sometimes, and no, (3 radio buttons) each of which have a corresponding value, 10, 5, and -10 respectively.
I had the questions divided up amongst 4 headings with several questions under each heading.
I was able to post all the data to mySQL Database by giving each a different name attribute that corresponded with its field in the Database.
The problem I am having is that I can no longer use the radio buttons as a set, that is, they are all selectable, defeating the purpose of having them, essentially making them check-boxes....
I need to have each radio button its own value in my database and I need them to be grouped in their 3 possible choices for each question...
I will post an example of my form html and php send script....
Thank you in advance for any advice...
html code one question
<div class="questionBox">
<p>1.Have I clearly defined my companies target market?</p>
<input type="radio" name="ca1y" value="10"/>
<label for="ca1">YES</label>
<input type="radio" name="ca1s" value="5"/>
<label for="ca1">SOMEWHAT</label>
<input type="radio" name="ca1n" value="-10"/>
<label for="ca1">NO</label>
</div>
/* php post update */
$radioPost="INSERT INTO questions
( ca1y,
ca1s,
ca1n,...)
VALUES
( '$_POST[ca1y]',
'$_POST[ca1s]',
'$_POST[ca1n]',...)
I tried to give each radio button an ID attribute and use that to update the database but I can't seem to get that to work....
any help would be greatly appreciated
cheers.
I'm not sure if I'm getting the jist of what you trying to do, but it seems like you need to save an individuals answers to different questions to the DB but that each question can only have ONE of let's say three possible answers. Well, in that case you might think of redesigning your DB to look something like this:
You store the users details in the users table, the question details in the questions table and the different answers in the answers table. A user will be able to answer multiple questions but can only answer a particular question once. You then save the answer in ONE field called answer_value for example. There is no need to store the answer in multiple fields since you will be storing the VALUE of the radio button they chose, i.e you will store either a 10, 5 or -10 depending on which radio option was selected.
It's also important that in your HTML you name all the radio buttons for a particular question the same. This ensures that the radio options act as radio buttons and not as checkboxes. Your HTML would most likely look something like this:
<div class="questionBox">
<p>1.Have I clearly defined my companies target market?</p>
<input type="radio" name="q1" value="10"/>
<label for="ca1">YES</label>
<input type="radio" name="q1" value="5"/>
<label for="ca1">SOMEWHAT</label>
<input type="radio" name="q1" value="-10"/>
<label for="ca1">NO</label>
</div>
<div class="questionBox">
<p>2.Have I clearly defined my companies product?</p>
<input type="radio" name="q2" value="10"/>
<label for="ca2">YES</label>
<input type="radio" name="q2" value="5"/>
<label for="ca2">SOMEWHAT</label>
<input type="radio" name="q2" value="-10"/>
<label for="ca2">NO</label>
</div>
.....
Note that question 1 has 3 radio options all named "q1" and question 2 has 3 radio options all named "q2". Follow the same convention for all your questions. Your PHP then becomes pretty straightforward and will probably look something like this:
$radioPost="INSERT INTO answers (user_name, question_name, answer_value)
VALUES (('$_POST[user_name]', 'q1', '$_POST[q1]),('$_POST[user_name]', 'q2', '$_POST[q2]), ....)
If you not sure what the radio button names are, you can use a foreach loop as follows:
$user = $_POST[user_name];
foreach ( $_POST as $key => $val )
{
If ($key <> 'user_name') //you might need to check that you only reading the radio options
{
$radioPost="INSERT INTO answers (user_name, question_name, answer_value)
VALUES ('$user', $key, '$val')"
....
}
}
Also be advised that even if you only using radio options, you should still clean the inputs to prevent attacks like SQL-Injection etc. I suggest you find some more info on securing your code against attack.
BTW, if you place the questions in a table of it's own, you can dynamically create your questionnaire from this table, which then allows you to add or delete questions at will, making your whole application a lot more flexible. And saving your answers in one field instead of three, will remove all the NULL values from your table, which will simplify your queries when you perform calculations. I know MySQL normally puts a zero as the default integer value, but it's still better to save it into one field. If you want to know which option a user chose for a particular question, just check the value stored in that field.
Not very good solution: write js to deselect appropriate radio buttons.
On more serious note i don't understand the need to have all radios with different names. Why is such solution not applicable: name radios in one question with same name, lets say question1, then after form post just look at value and from that you can easily update db. I suppose you want to collect how many times each radio was selected. So if you know that question1 had choice 1 you than also know that question1 did not have choices 2 and 3. Unless you collect data in other way or for other purpose, but then I think there need to be a bit more input from you about the purpose of this. Though I still think you can do this like i said, this would not need complex processing, id say rudimentary programming knowledge should suffice.