PHP - To Insert data from checkbox forms into MYSQL - php

This is my first website that makes use of server-side technology.
And it's also my first delving into PHP working along side MYSQL.
I've been working and learning as I go.
I've created a basic management page for a database of product entries for a small Prom Dress business.
I've been working on the functionality of a form that the administrator can use to upload new entries to the database.
Some of these entries include:
Dress Name [text input]
Colour Availability
[check boxes]
I've run into trouble getting data from multiple check boxes from a HTML form into the database.
The choices in the check boxes should represent a boolean value (yes/no - 1/0)
Here's the form structure:
<form action="inventory_list.php" enctype="multipart/form-data" name="myForm" id="myform" method="post">
<table width="90%" border="0" cellspacing="0" cellpadding="6">
<tr>
<td width="20%" align="right">Dress Name</td>
<td width="80%"><label>
<input name="Dress_name" type="text" id="Dress_name" size="64" />
</label>
</td>
</tr>
<tr>
<td align="right">Collections</td>
<td>
<label>
<select name="collections" id="collections">
<option value="other">Other</option>
<option value="hermione">Hermione</option>
<option value="jora">Jora</option>
<option value="manon">Manon</option>
</select>
</label></td>
</tr>
<tr>
<td align="right">Available Sizes</td>
<td>
<input type="checkbox" name="sizes[]" value="1" /> Sizes 2-6<br />
<input type="checkbox" name="sizes[]" value="1" /> Sizes 6-10 <br />
<input type="checkbox" name="sizes[]" value="1" /> Sizes 10-14<br />
<input type="checkbox" name="sizes[]" value="1" /> Sizes 14-18 <br />
<input type="checkbox" name="sizes[]" value="1" /> Sizes 18-22<br />
<input type="checkbox" name="sizes[]" value="1" /> Sizes 22-26 <br />
</td>
</tr>
<tr>
<td align="right">Dress Colours</td>
<td>
<input type="checkbox" name="colours[]" value="1" /> Pinks/Reds <br />
<input type="checkbox" name="colours[]" value="1" /> Blues/Greens <br />
<input type="checkbox" name="colours[]" value="1" /> Violet/Purple<br />
<input type="checkbox" name="colours[]" value="1" /> Yellow/Orange/Brown/Gold <br />
<input type="checkbox" name="colours[]" value="1" /> Black/White<br />
</td>
</tr>
<tr>
<td align="right">Product Image</td>
<td><label>
<input type="file" name="fileField" id="fileField" />
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="button" id="button" value="Add This Item Now" />
</label></td>
</tr>
</table>
</form>
And here is the PHP that I've built to deal with the form submitting data to the Database.
<?php
if (isset($_POST['Dress_name'])) {
$dress_name = mysql_real_escape_string($_POST['Dress_name']);
$collections = mysql_real_escape_string($_POST['collections']);
$sizesArray = $_POST['sizes'];
$coloursArray = $_POST['colours'];
foreach ($sizesArray as $key => $value)
{
echo "Key = $key || Value = $value<br />";
}
foreach ($coloursArray as $ckey => $cvalue)
{
echo "Key = $ckey || Value = $cvalue<br />";
}
//See if that product name is an identical match to another product in the system
$sql = mysql_query("SELECT ID FROM names WHERE Dress='$dress_name' LIMIT 1");
$productMatch = mysql_num_rows($sql); // count the output amount
if ($productMatch > 0) {
echo 'Sorry you tried to place a duplicate "Product Name" into the system, click here';
exit();
}
//Add this product into the database now
$sql = mysql_query("INSERT INTO names (Dress)
VALUES('$dress_name')") or die (mysql_error());
$pid = mysql_insert_id();
//Place image in the folder
$newname = "$pid.jpg";
move_uploaded_file( $_FILES['fileField']['tmp_name'], "../inventory_images/$newname");
header("location: inventory_list.php");
exit();
}
?>
As you can see, I've got as far as putting the data into an array. And now I've hit a bit of a brick wall, I can't seem to find an answer that makes sense anywhere.
How do I get the boolean values into correct columns in the database table?
Appreciate your time!

The first thing to know is that HTML checkboxes will return a result if checked, and will return nothing if unchecked. Therefore, it is important in your html to have your values increment:
<td align="right">Available Sizes</td>
<td>
<input type="checkbox" name="sizes[]" value="1" /> Sizes 2-6<br />
<input type="checkbox" name="sizes[]" value="2" /> Sizes 6-10 <br />
<input type="checkbox" name="sizes[]" value="3" /> Sizes 10-14<br />
<input type="checkbox" name="sizes[]" value="4" /> Sizes 14-18 <br />
<input type="checkbox" name="sizes[]" value="5" /> Sizes 18-22<br />
<input type="checkbox" name="sizes[]" value="6" /> Sizes 22-26 <br />
</td>
A fully normalized database schema would look something like this:
//Note that 'names' and 'collections are overloaded
//words and should be avoided
table BRANDS
id INT AUTOINCREMENT
collectionname VARCHAR
table SIZES
id INT AUTOINCREMENT
sizecategory VARCHAR //ie 'Sizes 18-22'
table COLOURS
id INT AUTOINCREMENT
colourname VARCHAR
table INVENTORY
id INT AUTOINCREMENT
brandid INT FOREIGN KEY (BRAND)
imageurl VARCHAR
table INVENTORY_SIZES
inventoryid INT FOREIGN KEY
sizeid FOREIGN KEY
table INVENTORY_COLOURS
inventoryid INT FOREIGN KEY
colourid FOREIGN KEY
Your BRAND, COLOURS and SIZES tables would need to be properly populated with your available options, and you could in theory dynamically load your page with data from those tables. The ids of each of the rows in those tables should end up as the values in your checkbox arrays.
//get your inputs
$query_values = array();
$query_values[':brandid'] = $dress_name = $_POST['Dress_name'];//note that you should change the value in your options here to the unique ids in your database.
$query_values[':sizeid'] = getSize($_POST[]);
$query_values[':colourid'] = getColour($_POST[]);
$query_values[':quantity'] = $_POST['quantity'];
$query_values[':imageurl'] = $_POST['imageurl'];
//Prepare and execute your sql
//Note that PDO will handle escaping problematic inputs.
$sql = "INSERT INTO INVENTORY ('brandid', 'imageurl') VALUES (:brandid, :sizeid, :colourid, :quantity, :imageurl)";
executeInsert($sql, $query_values);
$inventoryid = mysql_insert_id();
saveSizes($_POST['sizes'], $inventoryid);
saveColours($_POST['colours'], $inventoryid);
function saveSizes($size_array, $inventoryid) {
$sql = "INSERT INTO INVENTORY_SIZES ('inventoryid', 'sizeid') VALUES (:inventoryid, :sizeid)";
foreach ($size_array as $sizeid) {
$query_values = array();
$query_values[':inventoryid'] = $inventoryid;
$query_values[':sizeid'] = $sizeid;
executeInsert($sql, $query_values);
}
}
function saveColours($colour_array) {
$sql = "INSERT INTO INVENTORY_COLOURS ('inventoryid', 'colourid') VALUES (:inventoryid, :colourid)";
foreach ($size_array as $sizeid) {
$query_values = array();
$query_values[':inventoryid'] = $inventoryid;
$query_values[':colourid'] = $colourid;
executeInsert($sql, $query_values);
}
}
function executeInsert($sql, $query_values) {
$query = $conn->prepare($sql);
$query->execute($query_values);
}
Be sure to use PHP PDO to guard against security issues. I'm fairly sure some of that could be abstracted out/cleaned up better, but this should do the job. (Though I'm also fairly sure there are little bugs as I'm doing this cold and without testing.)

You need to place the insert statement in an 'else' statement after the 'if' which checks if the name already exists in the database.
I am not sure what exactly you are trying to do , since there is no statement that you are executing to put the 'checkbox' values in the database. You are echo-ing the sizes array to as an output for the administrator to see after he submits this form ,but you are not putting it in the database at all.
What will help is if you can share the database structure ( the column names) . If you don't have any columns for sizes 2-5 & other categories , add those & then change your insert statement to the following :
INSERT INTO names (Dress,Size2to5,Size5to10,Size10to15,Size15to20) VALUES('$dress_name','$size[0]','$size[1]','size[2]','size[3]')
Hope this helps. Do let us know if this works for you.

Related

how do i select multiple mysql records based on checked checkboxes?

on page 1 i have a form, then on page 2 which is the processor file, i want to select records based on the checked checkboxes that were checked on page 1.
<form action="output.php" method="post">
<input type="checkbox" id="" class="" name="check_list[]" value="something" />
<input type="checkbox" id="" class="" name="check_list[]" value="something else" />
<input type="checkbox" id="" class="" name="check_list[]" value="yet another thing" />
<input type="checkbox" id="" class="" name="check_list[]" value="one more thing" />
<input type="checkbox" id="" class="" name="check_list[]" value="some name" />
<input type="checkbox" id="" class="" name="check_list[]" value="some other name" />
<input type="submit" value="Submit" name="submit">
</form>
the following foreach can display all the values of everything that was checked, but i don't know how to take it further into my sql select statement to select all the records that have a column field by that name.
foreach($_POST['check_list'] as $check) {
echo $check . '<br>';
}
lets say in a table called stuff there are these fields
id, first_title, second_title
so i want to do the following, but obviously this isn't the way to write it. this is the part i need help with.
SELECT * FROM stuff WHERE first_title = $check or second_title = $check
lets us further say that these records exist in the table...
id first_title second_title
-----------------------------------------
1 something something else
2 yet another thing one more thing
3 some name some other name
then lets say these checkboxes were checked:
<input type="checkbox" id="" class="" name="check_list[]" value="something" />
<input type="checkbox" id="" class="" name="check_list[]" value="one more thing" />
so what i want to happen is for my select statement to select record 1 and record 2 and not record 3, because "something" is in the first_title column of the first record, and "one more thing" is in the second_title of the second record, and nothing was checked that is in third record.
i hope i gave as much detail as is needed. let me know if you need further explanation.
Use the SQL IN operator to test if a column is in a list of values. Here's how to write it with MySQLI:
$in_str = implode(', ', array_map(function($title) use ($con) {
return "'" . $con->real_escape_string($title) . "'";
}, $_POST['check_list']));
$sql = "SELECT * FROM stuff WHERE first_title IN ($in_str) OR second_title IN ($in_str)";
$result = $con->query($sql);
try this dynamic where condition in your code
<?php
$arr_where = array();
foreach($_POST['check_list'] as $check) {
$arr_where[] = " first_name='$check' OR last_name='$check' ";
}
$where_text = implode("OR", $arr_where);
$sql = "SELECT * FROM stuff WHERE ".$where_text;
?>

Registration Form - Checkbox Is Inserted on new rows in Database

I'm Practising PHP programming. I have made a Registration Form which has
2 Text Area (For First Name and Last)
2 Radio Buttons (For Gender Selection - Haven't started work on that yet)
8 Check boxes (4 each for Subject and Hobbies)
I have a Database Table by the name of persons which has
5 Columns (FirstName,LastName,Gender,Subject,Hobbies)
The Data from the form is being fetched, but each check box is inserted in the next row below the name.
For example David Bekham the subject php asp and hobby tv reading instead of appearing on the same row and against the name of the record, they appear on the next row.
As this is my first time, my question is
Q1 :- Is that how a record for such a form supposed to appear?
Q2 :- If not then where/what is the problem?
Q3 :- Could you either help me radio button code or provide me an easy link to learn it.
HTML FORM
<!DOCTYPE>
<html>
<head>
<title>Insert Data</title>
</head>
<body>
<h1> Insert to Register </h1>
<form name="form1" method="post" action="insert.php" >
<fieldset>
<legend> Registration Form </legend>
FirstName <input type="text" name="a" value="Enter firstname"/>
<br/><br/>
LastName <input type="text" name="b" value="Enter lastname"/>
<br/><br/>
<h3> Gender selection </h3>
Male <input type="radio" name="gender"/> female <input type="radio" name="gender"/>
<br/><br/>
<h3> Subject selection </h3>
<input type="checkbox" name="sb[]" value="php"/> PHP
<br/>
<input type="checkbox" name="sb[]" value="asp"/> ASP.NET
<br/>
<input type="checkbox" name="sb[]" value="html"/> HTML
<br/>
<input type="checkbox" name="sb[]" value="css"/> CSS
<br/><br/>
<h3> Hobbies selection </h3>
<input type="checkbox" name="hb[]" value="tv"/> Tv
<br/>
<input type="checkbox" name="hb[]" value="pc"/> Computer
<br/>
<input type="checkbox" name="hb[]" value="book"/> Reading books
<br/>
<input type="checkbox" name="hb[]" value="games"/> Games
<br/><br/>
<input type="submit" name="submit" value="Submit"/>
</fieldset>
</form>
</body>
</html>
php file
<!DOCTYPE>
<html>
<head>
<title>Processing_Insert_main</title>
</head>
<body>
<?php
// =============== code for Connection_SQLi ==============================
$con=mysqli_connect("localhost","root","","Ismat_db");
//check connection
if(mysqli_connect_errno())
{
echo "Cannot connect to mysqli:" . mysqli_connect_error();
}
// =============== code for Submit_input type ================================
if(isset($_POST['submit']))
{
// ========== code for Name_TextArea ===============
$sqlta = "INSERT INTO persons(FirstName,LastName)VALUES ('$_POST[a]','$_POST[b]')";
if (!mysqli_query($con,$sqlta))
{
die('Error: ' . mysqli_error($con));
}
echo "record added for name<br/>";
// ====== code for subject_checkbox ================
$s = $_POST['sb'];
$how_many=count($s);
for($i=0;$i<$how_many;$i++)
{
echo "You Selected: " .$s[$i]."<br/>";
if(!mysqli_query($con,"INSERT INTO persons(Subject) VALUES('$s[$i]')"))
{
echo "Not Recorded".mysqli_error($con);
}
echo "Record Added for subject<br/>";
}
// ============ Code for Hobbies_checkbox ========================
$h = $_POST['hb'];
$how_many=count($h);
for($i=0;$i<$how_many;$i++)
{
echo "You Selected: " .$h[$i]."<br/>";
if(!mysqli_query($con,"INSERT INTO persons(Hobbies) VALUES('$h[$i]')"))
{
echo "Not Recorded".mysqli_error($con);
}
echo "Record Added for Hobby<br/>";
}
//============================================================
echo '<br/>'.''. "Back" . '';
}
?>
</body>
</html>
$gender=$_POST['gender'];
$chkhobby=implode(',',$_POST['chkhobby']);
<tr>
<th>Gender</th>
<td>
Male<input type="radio" name="gender" checked="checked" value="1">
Female<input type="radio" name="gender" checked="checked" value="0">
</td>
</tr>
<tr>
<th>Hobbies</th>
<td>
read<input id="check_1" type="checkbox" name="chkhobby[]" value="read">
write<input id="check_2" type="checkbox" name="chkhobby[]" value="write">
play<input id="check_4" type="checkbox" name="chkhobby[]" value="play">
</td>
</tr>
How is your table structured? I would need to see the structure to be able to give you an actual query but it looks to me like you are inserting each value into the database as part of a separate query (which will always result in separate rows being inserted in the database). If you are storing the persons firstname, lastname, hobbies, and sports, etc in one row of your table you would need to do your query and insert values in 1 query not separate queries. So if you are currently doing:
"INSERT INTO persons(FistName, LastName)VALUES ('$_POST[a]','$_POST[b]')";
"INSERT INTO persons(Subject) VALUES('$s[$i]')"
"INSERT INTO persons(Hobbies) VALUES('$h[$i]')"
you should rather do:
"INSERT INTO persons(FistName, LastName, Subject, Hobbies) VALUES('$_POST[a]','$_POST[b]','$s[$i]','$h[$i]')"
Also for correct HTML standards compliance, readability, and accessibility for people with text readers etc. you should insert the text for each input as a label. So what I mean is instead of:
<input type="checkbox" name="sb[]" value="php"/> PHP
<br/>
<input type="checkbox" name="sb[]" value="asp"/> ASP.NET
you should use:
<input type="checkbox" name="sb[]" id="checkbox_php" value="php"/><label for="checkbox_php">PHP</label>
<br/>
<input type="checkbox" name="sb[]" id="checkbox_asp" value="asp"/><label for="checkbox_asp">ASP.NET</label>
Then you can use CSS to arrange the labels and checkboxes as you wish (float, etc). For checkboxes to appear correctly and vertically aligned with their labels I normally use tables. This is not ideal (as it's not the intended use of tables) but it gets around cross browser issues (and older browser issues) of the vertical alignment of these items in some browsers as well as keeps the label on the same line as the checkbox itself. For example:
<table>
<tr>
<td><input type="checkbox" name="sb[]" id="checkbox_php" value="php"/></td>
<td><label for="checkbox_php">PHP</label></td>
</tr>
</table>
On a side note your code is very vulnerable to SQL injection. You should read up about mysql_real_escape_string or mysqli_real_escape_string (if you use the MySQLi extensions).

how to increase/delete quantity of a product in PHP MySQL or javascript. Or how to insert a quantity value of a product along with a checkbox

How to increase/delete quantity of a product in PHP MySQL or javascript? Or how to insert a quantity value of a product along with a checkbox?
<form action="addtocart.php" method="post">
<table width="100%" cellspacing="20px">
<?php
include 'dbconnect.php';//for connection
$sql='select * from product';
$res = $dbconn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$res->execute();
$disp="<tr><th>Image</th><th>Product Name</th><th>Price</th><th>Add To Cart</th></tr>";
while($rs=$res->fetch())
{
if($rs['availableOnline']==1)
$isonline="Yes";
else
$isonline="No";
if($rs['availableInStore']==1)
$isstore="Yes";
else
$isstore="No";
$disp.="<tr>";
$disp.="<td><img src=".$rs['imageLink']." width=50 height=70></img></td>";
$disp.="<td>".$rs['name']."</td>";
$disp.="<td>$ ".$rs['price']."</td>";
$disp.="<td><input type=checkbox value=".$rs['idProduct']." name=items[] > Add Item</td></tr>";
$disp.="<tr><td> </td><td>Available Online : ".$isonline."</td><td>Available in Store :".$isstore."</td><td> </td></tr>";
}
echo $disp;
?>
<tr><td> </td><td><input type="submit" id="btnsubmit" value="Add To Cart" /></td></tr>
</table>
</form>
Let me show you with an example, for dynamic quantity change , we can use javascript
index.php
<a herf="#" onclick="increase()"> Increse</a>
<input type="number" min=0 max=100 id="quantity" name="quantity" value="1">
<a herf="#" onclick="decrease()"> Decrease</a>
<input type="checkbox" name="fruit[]" value="1">Orange<br>
<input type="checkbox" name="fruit[]" value="2">Banna<br>
<input type="checkbox" name="fruit[]" value="3">Kiwi<br>
javscript
We will used the 'id' to get the value of a number(input)
function increase()
{
e=parseFloat(document.getElementById("quantity").value);
e+=1;
document.getElementById('quantity').value=e;
}
function decrease(){
e=document.getElementById("quantity").value;
e-=1;
//to prevent from quantity going less than zero
if(e>0)
{
document.getElementById('quantity').value=e;
}
}
save.php
in second php we will use implode function to store multiple value
$quantity= $_POST['quantity'];
$fruit= implode(',' , $_POST['fruits']);
echo $fruit; //used that value to store in database result will be like this 1,2,5,6

How can I get value of a text box which is looped using post method to insert value in database?

I had following code.My textbox attend is looped for number of times.I want to get value of each attend when my form is post to insert value in database.
<form method="post" action="insert.php">
<label>Subject</label>
<input type="text" maxlength="30" name="subject" />
<label>Total Lectures</label>
<input type="text" maxlength="30" name="total" />
<table width="537" border="1">
<tr>
<td width="90">Name</td>
<td width="139">Roll Number </td>
<td width="136"> </td>
<td width="144">Attendence</td>
</tr>
<?php
$query=mysql_query("SELECT * FROM STUDENT");
$i=0;
while($rec=mysql_fetch_array($query)){
$i++;
?>
<tr>
<td><?php echo $rec['name']; ?></td>
<td><?php echo $rec['roll_number']; ?></td>
<td> </td>
<td><input type="text" maxlength="10" name="atten" /></td>
</tr>
<?php } ?>
</table>
<input type="submit" value="submit" />
</form>
and my insert.php page is
if($_SERVER['REQUEST_METHOD']=='POST'){
$query=mysql_query("SELECT * FROM STUDENT");
while($rec=mysql_fetch_array($query)){
$attend=$_POST['atten'];
$subject=$_POST['subject'];
$total=$_POST['total'];
$query1=mysql_query("INSERT INTO course VALUES('$i','$subject','$total','$attend','')") or die(mysql_error());
}
}
I am getting only 1 value of text box.
The problem is that you have many inputs all with the name atten. When you post this form, only one of those values will be carried forward.
If you change the name to atten[] all of the values would be posted as an array, which you would then have to loop through to build you insert query.
You could access this posted array as follows:
$attendee_array = $_POST['atten'];
foreach($attendee_array as $attendee) {
// perform insert or build insert query (prefereable as you can do all these inserts at once) here
// make sure to escape your data for input
}
Change the names of your inputs:
<input name="subject[]" value="Lorem" />
<input name="total[]" value="ipsum" />
<input name="atten[]" value="dolor" />
Then:
$_POST['subject'][0] == 'Lorem'
$_POST['total'][4] == 'amet'
If so, that would make my life ten times easier, as I could send an
indefinite amount of information through a form and get it processed
by the server simply by looping through the array of items with the
name "subject". etc.
You need to use input array like:
<input type="text" maxlength="10" name="attend[]" />
And then you will get all the values of attend in an array and you can loop through that $_POST['attend'].

Dynamic multidimensional post form

I have a form with a variable number of inputs. The inputs are inside the table and I need to get three values from them: the row, the column and the actual value inside the input.
Some may be populated some may not and I need all their values to update a mysql db (row and column to know what to update, value to know the new value to insert in the database).
This is my form (an example version of it):
<form method="post" action="">
<input name="data[111][222]" value="2" />
<input name="data[112][221]" value="0" />
<input name="data[113][223]" value="4" />
//goes on
<input name="data[324][435]" value="11" />
<input name="data[325][436]" value="" />
</form>
And that's as far as I go. How can I get the data from this form so I can do a simple update in my database that goes like this (for all the affected inputs):
update table set res="value_from_input" where row="row_value" and col="col_value"
<form method="post" action="">
<input name="data[111][222]" value="2" />
<input name="data[112][221]" value="0" />
<input name="data[113][223]" value="4" />
<input name="data[324][435]" value="11" />
<input name="data[325][436]" value="" />
<input type="submit" />
</form>
<?php
foreach ($_POST['data'] as $k1 => $v1)
{
foreach ($v1 as $k2 => $v2)
{
echo "<p>k1:".$k1."; k2: ".$k2."; value: ".$v2."</p>";
$query = "update table set res='$v2' where row='$k1' and col='$k2'";
mysql_query($query);
}
}
?>
foreach($_POST['data'] as $row => $row_array)
{
foreach($row_array as $col => $value)
{
// Sanitize all input data before entry
$mysql = "UPDATE table SET res='$value' WHERE row='$row' AND col='$col'";
}
}

Categories