Registration Form - Checkbox Is Inserted on new rows in Database - php

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).

Related

add values into selection table from multiple table

I have searched everywhere and still cannot find the answer. Can anybody help?
I have a PHP form that consists of a textbox (with data that will go into column name_id) and a checkbox, that has the option to go to 5 different MySQL tables:
'table A'
'table B'
'table C'
'table D'
'table E'
People can choose which table they want, and the name_id will go to the tables selected.
How can I do this?
my Answere in different from #RandD-SexyBoy- . my sql query is different from #RandD-SexyBoy- he has used $sql = "INSERT INTO $tables[$i](nameID_column); with out VALUES (:nameID_column)
were is have used $sql->prepare("INSERT INTO ".$v." (name_id) VALUES (?)"
Here are 3 cases the user responds
case first : user may select a single table
case second : user may select multiple tables. here we must use foreach() loop and dynamic sql queries.
case third : user may not select any table in this case we must give user a message table not selected
html form :
`
<html>
<head>
</head>
<body>
<form action="" method="post">
<input type="text" name="name_id" required>
<p>select your table to add data</p>
<input type="checkbox" name="tables[]" value="tblA">Table A<br>
<input type="checkbox" name="tables[]" value="tblB">Table B<br>
<input type="checkbox" name="tables[]" value="tblC">Table C<br>
<input type="checkbox" name="tables[]" value="tblD">Table D<br>
<input type="checkbox" name="tables[]" value="tblE">Table E<br>
<input type="submit" name="submit">
</form>
</body>
</html>
`
php file :
<?php
$con = new mysqli('localhost','root','admin','demo');
if(!$con){
die("Connection ".$con->connect_error);
}
if(isset($_POST['submit'])){
$name_id = $_POST['name_id'];
$tables = $_POST['tables'];
if(!empty($tables)){
foreach($tables as $key=>$v){
$sql = $con->stmt_init();
if($sql->prepare("INSERT INTO ".$v." (name_id) VALUES (?)")){
$sql->bind_param($name_id);
$sql->execute();
echo "DATA INSERTED";
}
else
{
echo "Error".$con->error;
}
}
}
else
{
echo "You have not selected tables";
}
}
?>
So one naive approach could be, when the user submits the form, on your php side, you check which checkboxes are ticked and your condition could be something like this
if(checkbox_for_table_A) {// insert query}
if(checkbox_for_table_B) {// insert query}
if(checkbox_for_table_C) {// insert query}
if(checkbox_for_table_D) {// insert query}
if(checkbox_for_table_E) {// insert query}
This way if one checkbox is selected it will save into that table, if more than one tables are selected, it will go in that table.
Hope this helps! Ask any doubt you get in the comment section.
Adapting from sources : post checkbox value and tutorial http://www.mustbebuilt.co.uk/php/insert-update-and-delete-with-pdo/, you can use this approach :
HTML Form :
<form action="checkbox-form.php" method="post">
<input type="text" name="name_id" /><br />
Select your database: <br/>
<input type="checkbox" name="formTables[]" value="A" />Table A<br />
<input type="checkbox" name="formTables[]" value="B" />Table B<br />
<input type="checkbox" name="formTables[]" value="C" />Table C<br />
<input type="checkbox" name="formTables[]" value="D" />Table D<br />
<input type="checkbox" name="formTables[]" value="E" />Table E<br />
<input type="submit" name="formSubmit" value="Submit" />
</form>
Now the PHP script :
<?php
$pdo_connection = new PDO('mysql:host=localhost;dbname=test', 'demouser', 'demopass');
$tables = $_POST['formTables'];
if(empty($tables))
{
echo("You didn't select any tables.");
}
else
{
$N = count($tables);
echo("You selected $N table(s): ");
for($i=0; $i < $N; $i++)
{
$sql = "INSERT INTO $tables[$i](nameID_column);
$stmt = $pdo_connection->prepare($sql);
$stmt->bindParam(':nameID_column', $_POST['name_id'], PDO::PARAM_STR);
$stmt->execute();
echo("Your ID Name was inserted into table $tables[$i] ! <br /> ");
}
}
?>

Need to carry check-box data from one page to another using PHP

I am new to php and am not quite clear on what to do to carry my information from the first page to the next and then submit it to my email when they are done filling out contact information.
I need the script to work as follows:
Step1: User clicks the input check-boxes for the field they want that is stored in an array
ex:
< input type="checkbox" name="Sound[]" value="item1" > item1
and clicks a button i have written as
< input type="image" name="Submit" class="" alt="" src="images/contact1.png" border="0" >
Step2: The information from the check-boxes they have clicked needs to be carried over to the next page where they will fill out their contact info. Name email phone etc.
ex:
<tr>
<td valign="top">
<label for="telephone">Telephone Number *</label>
</td>
<td valign="top">
<input type="text" name="telephone" maxlength="30" size="30" style="margin-bottom: 10px;">
</td>
</tr>
Step3. All of this information should be sent to my email upon button press for me to contact them :D
<tr>
<td colspan="2" style="text-align:center;">
<input type="image" name="Contact" class="contactbutton" alt="" src="images/contact.jpg"/>
</td>
</tr>
I can pull the information from my inputs but do not know how to carry to the next page!
Can I do it all in the same php script? or does each page need a different php script?
Please help!
Thanks Paul
you can do it with a form and send it to the page2.php. value will be stored in
$_POST['S'] for the checkbox
<form action="page2.php" method="post">
<input type="checkbox" name="S" value="item1" > item1
<input type="SUBMIT" >
</form>
------------------
page2.php
echo($_POST['S']); // will be item1
$_SESSION array is better. to use it you need to put session_start(); at start of
every page that will use your $_SESSION variable i.e
session_start();
if(isset($_POST['S'])){
$_SESSION['h'] = $_POST['S'];
echo($_SESSION['h']); } //output value in checkbox
?>
<html><body>
<form method="post">
<input type="checkbox" name="S" value="item1" > item1
<input type="SUBMIT" value="item1" >
Once this script is run you can accesS value in $_SESSION['h'] in other pages.
the data will be deleted when you close browser.
----------------------------------
page2.php
<?php
session_start();
if(isset($_SESSION['h'])){ //check if $_SESSION['h'] has been set a value
echo $_SESSION['h']; //output value stored in var
}
?>
You will ultimately still require the use of POST data to get the checkbox status from your page.
Page 1:
<?php
session_start();
// If postdata is received then redirect to next page
if(isset($_POST['Sound'])) {
$_SESSION['Sound'] = $_POST['Sound'];
header('Location: http://www.example.com/page2.php');
exit;
}
?>
<form method="post" action="page1.php">
Sound? <input type="checkbox" name="Sound" value="item1"><br>
<input type="submit">
</form>
Page 2:
<?php
session_start();
// If postdata is received then redirect to next page
if(isset($_POST['telephone']) && isset($_POST['email'])) {
$_SESSION['telephone'] = $_POST['telephone'];
$_SESSION['email'] = $_POST['email'];
header('Location: http://www.example.com/page3.php');
exit;
}
?>
<form method="post" action="page2.php">
<!-- If you want to output the previously saved data in a disabled item -->
Sound? <input type="checkbox" name="Sound" value="item1" disabled="disabled" <?php if($_SESSION['Sound'] == 'Yes') echo('checked="checked"'); ?>>
Telephone: <input type="text" name="telephone" value=""><br>
Email: <input type="email" name="email" value=""><br>
<input type="submit">
</form>
And so on and so forth for your next pages
This does not include the code for generating the e-mail via PHP but is intend to show you how you can take the form input/checkbox selections and store there values to a SESSION ARRAY. Note that in this example: The form is submitting to itself by leaving the action="" blank, but normal would submit to a external PHP file for parsing/handling.
Also, im choosing to create a random number to represent the visitor to the form if not specifically set by $_POST['user']
<?php session_start();
if (!isset($_SESSION['user'])) {$_SESSION['user']=rand(10,700);}
if (isset($_POST['user'])) {$id=$_POST['user'];} else {$id=$_SESSION['user'];}
?>
<form action="" method="post">
Sound 1:<input name="cb1" type="checkbox" value="sound1"><br>
Sound 2:<input name="cb2" type="checkbox" value="sound2"><br>
Sound 3:<input name="cb3" type="checkbox" value="sound3"><br>
<input type="submit" name="submit" value="submit"><br><br>
<?php
if (isset($_POST['submit']) && $_POST!=="") {
foreach($_POST as $key => $value) {
$_SESSION['visitor']['sounds'][$id]=array(
'selects'=>$_POST['cb1'].",".$_POST['cb2'].",".$_POST['cb3']
);
};
echo "For user ID:".$id." We echo the comma delimited stored SESSION array: ".$_SESSION['visitor']['sounds'][$id] ['selects'];
echo "<br><br>";
// Option 2 Explodes the comma delimited ['selects'] field to handle each choice seperately
$choice = explode(",",$_SESSION['visitor']['sounds'][$id] ['selects']);
echo "For an alternative, we EXPLODE the stored 'selects' field of the SESSION ARRAY and can then echo each out seperately"."<br><br>";
echo "User ".$id." Option 1 value was: ".$choice[0]."<br>";
echo "User ".$id." Option 2 value was: ".$choice[1]."<br>";
echo "User ".$id." Option 3 value was: ".$choice[2]."<br>";
echo "<br><br>";
echo "A last example we loop through the EXPLODED values and echo only those that were selected (ie: had a value)"."<br>";
foreach ($choice as $key => $value ) { if ($value!=="") {echo "Selection: ".$value."<br>";} }
}
?>

How do I determine which dynamically-generated submit button was clicked in my PHP form?

I want to edit a dynamically-generated form (meaning: I don't know how many rows will be generated). This content is generated within a while loop, and the HTML generated has creates buttons of input-type=submit, generating as many identically-named buttons as there are iterations in the loop.
Of the generated buttons, I want to know which submit button has been clicked, in order to provide the user the same form for which it has been clicked. Disregard the name of the database and password to connect it; the connectivity is fine.
Feel free to suggest any new method to achieve the desired functionality.
The code is as follows:
echo "you have reached your travel details page. your recent travelling details are as follows".'</br>';
$dbc=mysqli_connect('localhost','xyz','xyz','abc') or die("connection to DB failed");
$query="SELECT * FROM travel_details WHERE emailid='{$_SESSION['username']}' ORDER BY dep_date DESC";
$result=mysqli_query($dbc,$query) or die("error in querying the DB");
?>
<h1>Your travel details are:-</h1>
<form name="showtraveldet" METHOD="POST" action="edittraveldet.php">
<table border="1">
<tr>
<th>Starting point</th><th>Ending point</th><th>No of passengers</th><th>Expected fare</th><th>Departure date</th>
<th>Departure time</th><th>Arrival Date</th><th>Arrival Time</th><th>Car Model</th><th>Car number</th>
<th>Who is driving</th><th>Driver's license number</th>
</tr>
<?php
while ($row=mysqli_fetch_array($result))
{
$tid=$row['travel_id'];
echo "the value of tid is '{$tid}'";
echo'<tr><td>'.$row['start_point'].'</td><td>'.$row['end_point'].'</td><td>'.$row['no_of_pass'].'</td><td>'.
$row['exp_fare'].'</td><td>'.$row['dep_date'].'</td><td>'.$row['dep_time'].'</td><td>'.$row['arr_date'].'</td><td>'.$row['arr_time'].'
</td><td>'.$row['car_model'].'</td><td>'.$row['car_no'].'</td><td>'.$row['who_is_driving'].'</td><td>'.$row['driver_license_no'].'</td>
<td><input type="submit" name="edit" value="Edit"></td></tr><input type="hidden" name="travelid" value="'.$row['travel_id'].' ;?>">';
}
edittraveldet.php :-
$travelid=$_POST['travelid'];
echo "the travel id in the variable is $travelid and got the value from '{$_POST['travelid']}'";
$dbc=mysqli_connect('localhost','xyz','xyz','abc') or die("connection to DB failed");
$query="SELECT * FROM travel_details WHERE travel_id='{$travelid}'";
$result=mysqli_query($dbc,$query) or die("error in querying the DB");
mysqli_close($dbc);
$row=mysqli_fetch_array($result);
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onsubmit="return validatewheregoing()" name="wheregoing">
<h1> Enter your travelling details so that other travellers can join you</h1>
<fieldset>
<legend> Travelling details </legend>
Start Point: <input type="text" name="start" value="<?php echo $row['start_point']; ?>"/><br />
End point: <input type="text" name="end" value="<?php echo $row['end_point']; ?>"/><br />
Passengers allowed: <input type="number" name="noofpass" value="<?php echo $row['no_of_pass']; ?>"/><br />
Expected Fare per passengers in rupees:<input type="number" name="fare" value="<?php echo $row['exp_fare']; ?>"/><br />
Departure Date:<input type="date" name="depdate" value="<?php echo $row['dep_date']; ?>"/><br/>
Departure time:<input type="time" name="deptime" value="<?php echo $row['dep_time'] ;?>"/><br/>
Arrival Date:<input type="date" name="arrdate" value="<?php echo $row['arr_date']; ?>"/><br/>
Arrival time at destination:<input type="time" name="arrtime" value="<?php echo $row['arr_time']; ?>"/><br/>
Car Model and name:<input type="text" name="cardet" value="<?php echo $row['car_det']; ?>"/><br/> <!--make this as a dropdown box for better database matching-->
Car Number:<input type="text" name="carno" /><br/><input type="checkbox" name="taxi" value="check this box if pooling a taxi">
Is the car self driven or driven by driver?<input type="radio" name="drivedet" value="Selfdriven" checked=""/>Self Driven<input type="radio" name="drivedet" value="driverdriven" />Driver driven<br />
Driver's License number<input type="text" name="licence_no"/></br>
<input type="checkbox" name="taxi" value="check this box if pooling a taxi"></br>
<input type="hidden" name="travelid" value="<?php echo $travelid ;?>" />
<input type="submit" value="invite travellers" name="editwheregoing"/>
</fieldset>
</form>
If only you can change your code, I would suggest you put the form tag itself in the while loop, each having the same action pointing to the same url but submitting different information to the destination page. This way you don't have to worry about the button clicked
while($row=mysqli_fetch_array($result))
{
//<form action="sameactionurl.php" name="form_1">
//<input type="hidden" name="travelid" value="$row['travelid']" />
//</form>
}
Another solution, if you don't want to change your code is use JavaScript to set a common hidden field to the value of the current ID before submitting the form
Name your submit buttons in a standard fashion and append a 3-digit number to the end, "button_XXXX_###" where ### is the number and XXX was the original name of your button.
After submission, check your request parameters for all variables starting with name "button_XXXX", and split the actual name "button_XXXX_####" by '_' character, and the "###" suffix will reveal the number of the button pressed.
It might be easier to create a form for each row instead, though.

PHP - To Insert data from checkbox forms into MYSQL

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.

Searching and retrieving value from database through checkbox selection

I need help ... that too from scratch as now am learning php. just variable declaration i am learning.
I have created a form with 5 check boxes. when i select any 1 or any 2, 3.. or any combination, i should get the data which is already stored for that option in MySQL database.
My form is this:
<form method="post" action="search.php" name="search_form" onsubmit="return checkCheckBoxes(this);">
<input type="checkbox" name="search1" value="qwerty_keypad" id="search1">QWERTY Keypad
<input type="checkbox" name="search2" value="touch_screen" id="search2"> Touch Screen
<input type="checkbox" name="search3" value="usb" id="search3"> SUB Drive
<input type="checkbox" name="search4" value="mobile_tracker" id="search4">Mobile Tracker
<input type="checkbox" name="search5" value="Backup" id="search5">Phone backup on MMC
<input type="submit" value="Search" /> </form>
what i should write in search.php.
Please help me ... please
Thanks in advance
Use an array to submit the values
<input type="checkbox" name="search[connectivity]" value="usb" id="search3"> USB
<input type="checkbox" name="search[display]" value="touchscreen" id="search4">Touchscreen
Afterwards you build your query based on those values:
foreach($_POST['search'] as $k=> $search){
$where[]= $k." = '".mysql_real_escape_string($search)."'";
}
$query = "Select * from table where ".implode(' AND ',$where);

Categories