How to post array data from a form to mysql DB - php

please forgive naivety and innocence...I am not a programmer! I have spent the best part of 4 days on this and I am ready for a PHP lesson or intense therapy.
Scenario: DB built in mySQL. Table with all columns varchar(50) except ID and age - both INT. See below, I just need a 'Yes' value in the checkbox linked colums/fields.
I want to insert data with a form that has both textboxes and checkboxes. I thought best way to do this was php array...??
Form:
<form action="process.php" method="post" enctype="multipart/form-data">
<label>Childname
<input type="text" name="textfield[childname]" />
</label>
<p>
<label>Age
<input type="text" name="textfield[age]" />
</label>
</p>
<p>
<label>Parent Name
<input type="text" name="textfield[parent_name]" />
</label>
</p>
<p>
<label>Contact Number
<input type="text" name="textfield[contact_no]" />
</label>
</p>
<p>Subjects<br />
<label>
<input type="checkbox" name="checkbox[scratch]" value="checkbox" />
Scratch</label>
<label>
<input type="checkbox" name="checkbox[app_inventor]" value="checkbox" />
App Inventor</label>
<label>
<input type="checkbox" name="checkbox[html]" value="checkbox" />
HTML</label>
</p>
<p>Sessions Attended<br />
<label>
<input type="checkbox" name="checkbox[nov12]" value="checkbox" />
Nov 2012</label>
</p>
<p>
<label>
<input type="checkbox" name="checkbox[dec12]" value="checkbox" />
Dec 2012</label>
</p>
<p> </p>
<p>
<label>
<input type="submit" name="Submit" value="Submit" />
</label>
</p>
</form>
PHP script:
<?php
include("config.php");
$childrecord = array("childname","age","parent_name","contact_no","scratch","app_inventor","html");
if(isset($_POST['childrecord'])){
$childrecord = $_POST['childrecord'];
$i = 0;
foreach ($childrecord as $key => $value); {
$i++;
$sql="INSERT INTO tblchildren (childrecord) VALUES ($_POST['childrecord'])";
mysql_query($sql);
}
?>
Please help!
Thanks in advance....

You want to store your form data in your code.
For this you have to make following changes in your code and database.
In Form
note: Input field value should be relevant.
With your existing html code your process.php will get data in this structure
Array
(
[textfield] => Array
(
[childname] => dang
[age] => 18
[parent_name] => doctor
[contact_no] => 100
)
[checkbox] => Array
(
[scratch] => checkbox
[app_inventor] => checkbox
[html] => checkbox
[nov12] => checkbox
[dec12] => checkbox
)
[Submit] => Submit
)
So you need to modify your process.php
Before that you have to modify structure of your table, follow these steps
1. Delete your existing table
2. Create new table
DROP TABLE tblchildren ;
CREATE TABLE tblchildren
(
id INT AUTO_INCREMENT PRIMARY KEY,
childname VARCHAR(30),
age TINYINT,
parent_name VARCHAR(30),
contact_no VARCHAR(20),
scratch ENUM('yes','no'),
app_inventor ENUM('yes','no'),
html ENUM('yes','no'),
sesNov12Attnd ENUM('yes','no'),
sesDec12Attnd ENUM('yes','no')
);
Since you are new to php so i have used basic function,
I will suggest you to use switch from mysql to mysqli
process.php
<?php
$con=mysql_connect("hostname","username","pass");
$db=mysql_select_db('dbname', $con);
//check form is submitted
if(isset($_POST)){
//mysql_real_escape_string() prevents from sql injection.
$childname= mysql_real_escape_string($_POST['textfield']['childname']);
$age=mysql_real_escape_string($_POST['textfield']['age']);
$parentName=mysql_real_escape_string($_POST['textfield']['parent_name']);
$contactNo=mysql_real_escape_string($_POST['textfield']['contact_no']);
$scratch=isset($_POST['checkbox']['scratch'])?'yes':'no';
$appInventor=isset($_POST['checkbox']['app_inventor'])?'yes':'no';
$html=isset($_POST['checkbox']['html'])?'yes':'no';
$nov12=isset($_POST['checkbox']['nov12'])?'yes':'no';
$dec12=isset($_POST['checkbox']['dec12'])?'yes':'no';
$sql="INSERT INTO tblchildren(childname, age, parent_name, contact_no, scratch,app_inventor,html, sesNov12Attnd, sesDec12Attnd )
VALUES
('$childname',$age,'$parentName','$contactNo','$scratch','$appInventor','$html','$nov12','$dec12')";
mysql_query($sql);
}else{
echo "Form Not SUbmitted";
}
?>

Related

store multiple value with same input name in sql

I need to insert the value of form into the data table.
here is my form for taking a test.
<form method="post" action="">
1<input type="text" name="answer">
3<input type="text" name="answer">
5<input type="text" name="answer">
7<input type="text" name="answer">
<input type="submit" name="submit">
</form>
how to store this all answer in one field of the data table
i have tried this code but its not storing all value
if(isset($_POST['submit']))
{
$answer = json_encode($_POST['answer']);
$query = "INSERT INTO `test` (`answer`) VALUES ('$answer')";
mysqli_query($con, $query);
if (mysqli_query($con, $query)) {
echo "inserted ";
} else {
echo "Error updating record: " . mysqli_error($con);
}
}
Try changing your HTML code to this.
<form method="post" action="">
1<input type="text" name="answer[]">
3<input type="text" name="answer[]">
5<input type="text" name="answer[]">
7<input type="text" name="answer[]">
<input type="submit" name="submit">
</form>
When you submit the form the $_POST['answer'] would look something like this
Array
(
[answer] => Array
(
[0] => first answer
[1] => second answer
[2] => third answer
[3] => fourth answer
)
)
Above is a printout of $_POST variable like so print_r($_POST)
Now you can easily get all the answer inputs inside PHP and have it converted to json like so
$answer = json_encode($_POST['answer']);
However since you are saving this inside mysql I would suggest using serialize() instead of json_encode(). Please read about serialize() https://www.php.net/manual/en/function.serialize.php

Array displaying only one record

Friends,
I apologize in advance for posting this question again.
I got great help from Barmar in resolving the problem I was having with displaying array results to users.
The error issue was resolved and result was being displayed.
Problem is the array displays one record.
When we insert multiple rows of records, only one record is displayed.
Does anyone know what could be wrong?
Basically, by default, a user is presented with one row of textboxes.
If user needs to add additional records, the user clicks the Add button to dynamically add an additional row of textboxes,
The code below is from a page called preview.php. It is supposed to capture all records entered in markup page by the user and displays them so user will have the option to review the records and go back to make changes if needed or submit records if everything is ok.
So far as indicated above, it displays only one record regardless of whether the user created one row or multiple rows.
We would like to capture all rows.
Any ideas what I might be missing with code below?
I apologize in advance. I have to show this tomorrow at work and it has occupied my entire weekend.
<?php
//echo "DEBUG POST DATA: <pre>".print_r($_POST, 1)."</pre>";
if(isset($_POST['employeename']))
$employeename = $_POST['employeename'];
if(isset($_POST['ttitle']))
$ttitle = $_POST['ttitle'];
echo $employeename .'<br>';
echo $ttitle .'<br> <hr width=400 align=left>';
$rowIDs = $_POST['rowIDs'];
for ($id = 0; $id < $rowIDs; $id++){
$sourcename1 = $_POST['sourcename1'][$id];
$sourceaddress1 = $_POST['sourceaddress1'][$id];
$income1 = $_POST['income1'][$id];
echo $sourcename1 .'<br>';
echo $sourceaddress1.'<br>';
echo $income1.'<br>';
}
?>
DEBUG POST DATA:
Array
(
[employeename] => Catherine Duffy
[ttitle] => Sr. Systems Analyst
[rowIDs] => 1
[sourcename1] => Array
(
[0] => Mark
Zverkov
)
[sourceaddress1] => Array
(
[0] => Address1
)
[income1] => Array
(
[0] => $79,000.00
)
[sourcename13] => Jim Brown
[sourceaddress13] => 32 Xooker Rd
[income13] => $99,000.00
[spousename] =>
[spouseAddress] =>
[spouseIncome] =>
[dividentname] =>
[dividentaddress] =>
[dividentAmt] =>
[reimbursmentName] =>
[reimburseAddr] =>
[remursementAmt] =>
[inputHonoraria] =>
[giftname] =>
[giftaddress] =>
[giftamount] =>
[orgname] =>
[orgaddresss] =>
[donationamt] =>
[creditorname] =>
[creditoraddress] =>
[creditAmt] =>
[email] =>
[submitted] => true
)
Catherine Duffy
Sr. Systems Analyst
Mark Zverkov
Address1
$79,000.00
//Markup
<script id="row-template" type="text/x-handlebars-template">
<div>
<!--reseed attribute IDs in case of gap resulting from deletions -->
<input type="hidden" name="rowIDs[]" value="{{rowNumber}}" />
<div class="form-group">
<label for="sourcename{{rowNumber}}">Name</label><br>
<input type="text" name="sourcename1{{rowNumber}}" id="sourcename1{{rowNumber}}" value="" class="required requiredField" />
<?php if($nameError != '') { ?>
<span class="error"><?=$nameError;?></span>
<?php } ?>
</div>
<div class="form-group">
<label for="sourceaddress1{{rowNumber}}">Address</label><br>
<input type="text" name="sourceaddress1{{rowNumber}}" id="sourceaddress1{{rowNumber}}" style="width:250px;" class="form-control" value="" class="required requiredField" />
<?php if($nameError != '') { ?>
<span class="error"><?=$nameError;?></span>
<?php } ?>
</div>
<div class="form-group">
<label for="income1{{rowNumber}}">Income</label><br>
<input type="text" style="width:250px;" class="form-control" name="income1{{rowNumber}}" id="income1{{rowNumber}}" value="<?php if(isset($_POST['spouseIncome{{rowNumber}}'])) echo $_POST['spouseIncome{{rowNumber}}'];?>" class="required requiredField" />
<?php if($nameError != '') { ?>
<span class="error"><?=$nameError;?></span>
<?php } ?>
</div>
<input id="Button{{rowNumber}}" type="button" rel="remove-row" value="Remove" />
</div>
</script>
<div id="addrow">
<div>
<!--reseed attribute IDs in case of gap resulting from deletions -->
<input type="hidden" name="rowIDs[]" value="{{rowNumber}}" />
<div class="form-group">
<label for="sourcename">Name</label><br>
<input type="text" name="sourcename1[]" id="sourcename1" value="" class="required requiredField" />
<?php if($nameError != '') { ?>
<span class="error"><?=$nameError;?></span>
<?php } ?>
</div>
<div class="form-group">
<label for="sourceaddress1">Address</label><br>
<input type="text" name="sourceaddress1[]" id="sourceaddress1" style="width:250px;" class="form-control" value="" class="required requiredField" />
<?php if($nameError != '') { ?>
<span class="error"><?=$nameError;?></span>
<?php } ?>
</div>
<div class="form-group">
<label for="income1">Income</label><br>
<input type="text" name="income1[]" id="income1" style="width:250px;" class="form-control" value="" class="required requiredField" />
<?php if($nameError != '') { ?>
<span class="error"><?=$nameError;?></span>
<?php } ?>
<input type="button" value="Add More" rel="add-row" />
</div>
</div>
</div><br><br>
From the code snippets and debug you posted, your PHP code appears to be expecting the data in a different format than your HTML form is generating. It's clear that you have a lot going on with the form, I might suggest starting a new, blank page and re-creating the form piece by piece to make sure each piece submits correctly before you add the next block of fields.
Specific to the question of receiving multiple records from the form, if you format your HTML for the part of the form that gets repeated (assuming {{ rowNumber }} gets replaced by 1, 2, 3,... each time a new one is added) like this:
<div class="this-div-gets-repeated">
<label>
Source Name:
<input type="text" name="source[{{ rowNumber }}][name]"/>
</label>
<label>
Source Address:
<input type="text" name="source[{{ rowNumber }}][address]"/>
</label>
<label>
Income:
<input type="text" name="source[{{ rowNumber }}][income]"/>
</label>
</div>
They you can expect to parse it in PHP like this:
<?php
$sources = isset($_POST['source']) ? $_POST['source'] : []; // just in case no sources are posted
foreach ($_POST['source'] as $id => $source) {
$sourcename = $source['name'];
$sourceaddress = $source['address'];
$income = $source['income'];
echo "$sourcename<br>$sourceaddress<br>$income<br>";
}
Edit: further comments on your HTML
Your HTML form has two blocks: a set of fields for the first "record", and then a repeating template for any additional records.
The first issue with your HTML is that your "first record" form fields have different names than your "more records" form fields:
Your "first record" form fields have fields like <input type="text" name="sourcename1[]"/>.
Your "more records" form fields have fields like <input type="text" name="sourcename1{{rowNumber}}"/>.
If you were to look at the HTML that gets generated once you've clicked "Add More" a couple times, your HTML would look like this:
<!-- the default "first record" -->
<input type="text" name="sourcename1[]"/>
<!-- from the first click on "Add More" -->
<input type="text" name="sourcename11"/>
<!-- from the second click on "Add More" -->
<input type="text" name="sourcename12"/>
From that you can see how the values entered into the "first record" fields will appear differently than the values from the dynamically-added "add more" fields?
It also appears that there's some weirdness happening with your Angular templates: your PHP $_POST contains the values from your "first record" fields (in [sourcename1] => Array), and there are values from your "add more" fields (in [sourcename13] => Jim Brown where {{rowNumber}} was 3), but are you intentionally starting {{rowNumber}} at 3 in Angular?

how to insert multiple checkbox values(which is integer data type) in same row with foreign key constraint

I know questions about multiple checkbox has been asked quite a few times but I am not able to workout with foreign key contraints. I have following 3 tables
table1: barber( bid int primary key, bname varchar(255))
table 2: services(sid int primary key, s_offered varchar(255))
table 3: appointments(bid int, sid int, app_time datetime, foreign key(bid) referecning barber(bid), foreign key(sid) references services(sid), primary key(bid, app_time))
I have a form in which I have sid as multiple checkbox values and i want the values of these sid to be in same row in appointments
I have following code it seems to be working but only one value of check box gets stored in database.
HTML code:
<label for="assigned_barber"> Desired Barber:</label>
<input type="radio" name= "bname" id="rick" value="rick"/>
<label for="rick"> Rick</label>
<input type="radio" name="bname" id="dave" value="dave"/>
<label for="dave"> Dave </label>
<input type="radio" name="bname" id="clarke" value="clarke"/>
<label for="clarke"> Clarke</label>
<input type="radio" name="bname" id="anyone" value="others"/>
<label for="anyone"> Doesn't matters</label><br><br>
<label for="service_desired"> Service Desired: </label>
<input type="checkbox" name="s_offered[]" id="fade" value="1"/>
<label for="fade"> Fade </label>
<input type="checkbox" name="s_offered[]" id="shave" value="2"/>
<label for="shave"> Shave </label>
<input type="checkbox" name="s_offered[]" id="scissors" value="3"/>
<label for="scissors"> Scissors </label><br><br>
<input type="submit" name="submit" value="submit"/>
<input type="reset" name="reset" value="rest"/>
</center>
and my php code is:
$bname=$_POST['bname'];
$s_offered = implode(';', $_POST['s_offered']);
mysqli_query($bd, "insert into appointment ( bid, sid, app_time) values ( (select bid from barbers where bname ='$bname'), '$s_offered', now())");
echo "the barber name is".""."$bname";
echo "service number is".""."$s_offered";
mysqli_close($bd);
but my main point is that how database mysql will handle this input? In my code I have used implode function which will separate the different inputs by ; (for eg. if user selects 2 checkboxes so in database table will it be 1;2 value stored) how will it be implemented because the field datatype in mysql is integer

PHP and MySQL Loop the same QueryString via GET

I am trying to do eCommerce filtering on the category page. So far I can get it to work for one colour, but if the user checks more than one colour, I want it to search for the other colour too.
URL
//current
category.php?colourChoice=White
//more than one
category.php?colourChoice=White&colourChoice=Ruby+Red
I realise I need some sort of form array or an explode?
MYSQL
products
---
id sku price
1 p22 45.00
2 p33 65.00
3 p44 70.00
colours
---
id sku name
1 p22 White
2 p33 Ruby Red
3 p44 Black
HTML
<form action="form.php" method="get">
<input type="checkbox" name="colourChoice" value="White"/>
<input type="checkbox" name="colourChoice" value="Black"/>
<input type="checkbox" name="colourChoice" value="Ruby Red"/>
<input type="checkbox" name="colourChoice" value="Orange"/>
<input type="submit" value="go">
</form>
PHP
// VARS
$colourName=mysql_real_escape_string($_GET["colourChoice"]);
// MYSQL
$checkSQL=mysql_query("
SELECT * FROM `products`
INNER JOIN `colours`
ON `products`.`sku` = `colours`.`sku`
WHERE (
name = '".$colourName."'
OR name LIKE '".$colourName.";%'
OR name LIKE '%;".$colourName.";%'
OR name LIKE '%;".$colourName."'
)
");
// SHOW RESULTS
while($r = mysql_fetch_array($checkSQL)) {
echo '
<div class="product">
Cost £'.$r['price'].'<br />
</div>
';
}
You have to make checkbox array as below
<form action="form.php" method="get">
<input type="checkbox" name="colourChoice[]" value="White"/>
<input type="checkbox" name="colourChoice[]" value="Black"/>
<input type="checkbox" name="colourChoice[]" value="Ruby Red"/>
<input type="checkbox" name="colourChoice[]" value="Orange"/>
<input type="submit" value="go">
</form>
Then, you will get multiple value checked into array in php.
foreach($_GET["colourChoice"] as $value){
/// here you can make concat for where clause.
}
You can get HTML input values in PHP as array:
HTML
<form action="form.php" method="get">
<input type="checkbox" name="colourChoice[]" value="White"/>
<input type="checkbox" name="colourChoice[]" value="Black"/>
<input type="checkbox" name="colourChoice[]" value="Ruby Red"/>
<input type="checkbox" name="colourChoice[]" value="Orange"/>
<input type="submit" value="go">
</form>
Then you query the database using prepare/execute statements to prevent SQL injection.
PHP
$placeholders = substr(str_repeat('?, ', count($_GET['colourChoice']), 0, -1);
$query = "
SELECT * FROM `products`
INNER JOIN `colours`
ON `products`.`sku` = `colours`.`sku`
WHERE name in ($placeholders);
");
$db = new PDO(...);
$stmt = $db->prepare($query);
$stmt->execute($_GET['colourChoice']);
print_r($stmt->fetchAll());

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