Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am trying to create sign up form, where it has multiple text field (name, email, phone, ..) and have multiple checkbox options.
I also created multiple tables in mysql database, one for each checkbox.
My goal is to store values in text field to selected checkbox data table.
My question is how can I create if statement to look what checkbox is selected, so it will store input of text field to that table
input.php
<html>
<head>
</head>
<script type="text/javascript">
function toggle(source) {
checkboxes = document.getElementsByName('chk1[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
<body>
<h2><font color="white">Welcome to Cars and Coffee</h2>
<p>Sign up to receive if you are interested in
receiving information from Cars and Coffee.</p>
<p>Please select at least one option</p>
<form name="newEntry" action="page.php" method="POST">
name<input type=text length=60 size=30 name="name"><br>
email<input type=text length=60 size=30 name="email"><br>
car<input type=text length=60 size=30 name="car"><br>
phone<input type=text length=60 size=30 name="phone"><br>
<input type="submit" name="submit" email="add" car="add" phone="add" >
</form>
<form action="page.php" method="POST">
<input type="checkbox" name="chk[]" value="cars_coffee">Cars & Coffee<br>
<input type="checkbox" name="chk[]" value="kentucky">Kentucky Derby Party<br>
<input type="checkbox" name="chk[]" value="july">July 4th<br>
<input type="checkbox" name="chk[]" value="labor">Labor Day<br>
<input type="checkbox" name="chk[]" value="new_year">New Years Day<br>
<input type="checkbox" name="chk[]" value="all" onClick="toggle(this)">Select All<br>
</form>
<?php
mysql_connect("localhost", "db", "pw");
mysql_select_db("db");
$qh = mysql_query("select * from all_emails order by id desc");
if (#mysql_num_rows($qh)) { /* the if(#...) syntax makes PHP supress any
warnings that might come out of that function. */
/* mysql_fetch_object(query handle);
* returns an object whose contents are that of one rotw in the
database. */
while ($obj = mysql_fetch_object($qh)) {
echo "
<p>
$obj->email<br>
$obj->name<br>
$obj->car<br>
$obj->phone<br>
<p>
<hr>
";
}
}
?>
</body>
</html>
page.php
<?php
mysql_connect("localhost", "db", "pw");
mysql_select_db("db");
mysql_query("insert into all_emails (name, email, car, phone) values ('".$_POST['name']."','".$_POST['email']."','".$_POST['car']."', '".$_POST['phone']."' )");
?>
<html>
<head>
<meta http-equiv=refresh content="0; URL=./input.php">
</head>
</html>
Here is the if statement I am trying.
<?php
mysql_connect("localhost", "db", "pw");
mysql_select_db("db");
if( isset($_POST["cars_coffee"] ) ) {
$sql = "INSERT INTO cars_and_coffee (name, email, car, phone) values ('".$_POST['name']."','".$_POST['email']."','".$_POST['car']."', '".$_POST['phone']."' )");
mysql_query($sql) or die(mysql_error());
}
echo "Record is inserted";
}
?>
Hi use the following code :
NOTE : I highly suggest you to use mysqli or PDO. mysql functions are deprecated and are obsolate.
Please sanitize or safe cast your data before inserting into your database.
Also NOTE: In form I am redirecting to the same form page. Please use the appropriate php file name or routing path.
db_connect.php
$host = 'localhost';
$user = 'root';
$password = 'root';
$database = 'skerp';
$connection_error = 'Sorry!!! We are experiencing problems with the database settings';
$link = mysqli_connect($host, $user, $password, $database) or DIE($connection_error);
The following is the implementation
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if($_SERVER['REQUEST_METHOD'] == 'POST'){
include_once ('db_connection.php');
if(in_array('cars_coffee', $_POST['chk'])){
$emails = mysqli_query($link, "INSERT INTO all_emails (name, email, car, phone) VALUES ('".$_POST['name']."','".$_POST['email']."','".$_POST['car']."', '".$_POST['phone']."' )");
}else{
//If it fails then put the condition here or you may skip else part
echo 'Not Exists';
}
echo '<pre>';
print_r($_POST);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<input type="checkbox" name="chk[]" value="cars_coffee">Cars & Coffee<br>
<input type="checkbox" name="chk[]" value="kentucky">Kentucky Derby Party<br>
<input type="checkbox" name="chk[]" value="july">July 4th<br>
<input type="checkbox" name="chk[]" value="labor">Labor Day<br>
<input type="checkbox" name="chk[]" value="new_year">New Years Day<br>
<input type="checkbox" name="chk[]" value="all" onClick="toggle(this)">Select All<br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
Hope it helps. Happy Coding!
You can use the isset method to check if a checkbox was selected.
if ( isset ( $_POST ["cars_coffee"] ) )
{
// do something
}
if ( isset ( $_POST ["kentucky"] ) )
{
// do something else
}
...
There seems to be a slight problem with your logic because you are using checkboxes to retrieve data from the user. If you want the user to only select one checkbox, use a radio button. That will make them unable to select multiple. If I'm just not understanding you correctly and you really do want users to be able to select multiple boxes, then keep using checkboxes, but change the name attribute of each checkbox to be unique. Because right now, every checkbox has the same name, so it is going to read only the last checkbox that they checked.
The logic would go something like this if you continued using checkboxes and gave each checkbox a unique name:
$sql = '';
// make sure that the checkbox is set
if(isset($_POST['kentucky_checkbox'])){
{
$sql += 'INSERT INTO kentucky VALUES ...;';
}
if(isset($_POST['labor_checkbox'])){
{
$sql += 'INSERT INTO labor VALUES ...;';
}
etc.
...
// execute $sql
The logic would go something like this if you used radio buttons:
// make sure that the variable is set
if(isset($_POST['chk[]'])){
{
// check what the value is
switch ($_POST['chk[]']) {
case 'option1':
// set the table
$table = 'table1';
break;
case 'option2':
$table = 'table2';
break;
case 'option3':
$table = 'table3';
break;
}
}
...
$sql = 'INSERT INTO ' . $table . ' VALUES ...';
Related
I am trying to displaying the input fields depending upon the what outputs are coming from the database. Please share any idea or logic in this. I have more than 25 fields.
Page1.php
I have Name(Text type), Email(Email type), gender(Radio), country(Select dropdown), Address( Textarea) in the form. The user will click on check box whatever he needs from the form and click on submit then the value of the fields which he selects will store in the database.
Form page
Page2.php
Here I am displaying the fields which are selected from Page1.php but also I need input type related to which fields come from the database.
For example: In the page1 I choose Name, Email, Country and submitted the form then In page2 I have to display the output <input type="text" name="Name">,<input type="text" name="Name">,<select></select>.
I need to know what logic I have to use it. Can any one help me with the script?
Form code
<form action="" method="post">
<input type="checkbox" name="check-fields[]" value="Name">
<label>Name(Text type)</label>
<input type="checkbox" name="check-fields[]" value="Email">
<label>Email(Email type)</label>
<input type="checkbox" name="check-fields[]" value="Gender">
<label>Gender(Radio type)</label>
<input type="checkbox" name="check-fields[]" value="Select">
<label>Country(Drop down)</label>
<input type="checkbox" name="check-fields[]" value="textarea">
<label>Address(Textare)</label>
<input type="submit" name="submit" value="submit">
</form>
Storing the value in the database
if (isset($_POST['submit'])) {
// prepare and bind
$a=$_POST['check-fields'];
$elements= implode(',',$a);
$sql_elements="INSERT INTO test (elements) VALUES (?)";
$stmt = $conn->prepare($sql_elements);
$stmt->bind_param("s", $elements);
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
}
Page 2
I am getting output but how can I set the input fields?
$sql_fields="SELECT elements FROM test WHERE id=3";
if ($stmt = $conn->prepare($sql_fields)) {
$stmt->execute();
$stmt->bind_result($elements);
while ($stmt->fetch()) {
$arr=explode(",", $elements);
echo "<pre>";
print_r($arr);
echo "</pre>";
}
}
$stmt->close();
$conn->close();
?>
You're trying to create a personalized form for different users if I'm correct, meaning that you will allow a user to generate a form based on a selection of fields the user can choose from.
What you need to do is create a table called "forminputtypes" where you create a row for each different input field you can think of, and want to give the user as a choice to select from. Your table would looke like this:
Id | FieldName | Type | etc ->
-------------------------------
1 | Name | text | ...
2 | Email | email | ...
3 | Gender | radio | ...
You can add more columns in the table to store more information (think of possible values in a radio input or a dropdown).
Now at in Page1.php you select all input types from this table, and display them like you already are. However, the value of these checkboxes will be the corresponding Id value of the record in the database like so:
<input type="checkbox" name="check-fields[]" value="3">
Now when someone chooses the Gender field, you can see in your Page2.php that the user did so by matching his choice '3' to the record in the database. If you want to save this information, you can create another table called UserFormInputFields which will function as a couple table between your user table and the FormInputTypes table.
When you want to display the form in Page2.php, you simply get all the input fields the user chose by selecting on Id from the FormInputTypes table. Since you know the type of each input field (because it's a column in the table) you can display them all correctly.
If you want to do it in core PHP only.Just put if else around the html tags.If value is coming from Database then you show particular tag else nothing. You can modify your page 2 code like.
<?php
$sql_fields="SELECT elements FROM test WHERE id=3";
if ($stmt = $conn->prepare($sql_fields)) {
$stmt->execute();
$stmt->bind_result($elements);
while ($stmt->fetch()) {
$arr=explode(",", $elements);
echo "<pre>";
print_r($arr);
echo "</pre>";
}
}
$stmt->close();
$conn->close();
?>
<form action="" method="post">
<?php if(in_array("Name",$arr)) { ?>
<input type="text" name="name" >
<label>Name</label>
<?php } ?>
<?php if(in_array("Email",$arr)) { ?>
<input type="email" name="email">
<label>Email</label>
<?php } ?>
<?php if(in_array("Gender",$arr)) { ?>
<input type="radio" name="gender" value="Male">
<input type="radio" name="geneer" value="Female">
<label>Gender(Radio type)</label>
<?php } ?>
//.............write other fiels like this.
<input type="submit" name="submit" value="submit">
</form>
I hope this helped.
I have two divs.
First div
Has inputs like checkbox and select.
<div>Events Selection</div>
Events <input type="checkbox" id="Option-1" checked="true">
Leaves <input type="checkbox" id="Option-2" checked="true">
Meetings <input type="checkbox" id="Option-3" checked="true">
Travels <input type="checkbox" id="Option-4" checked="true">
<div>Station Selection</div>
<select id="Filters1">
<option value="0">All Stations</option>
<option value="1">Main Station</option>
<option value="2">Sub Station</option>
<option value="3">Sub Station Main Office</option>
</select>
Second div
Has a SQL statement $sql = "SELECT * FROM events"; which i want to echo all those checked and selected options from First div.
So, my question is how to dynamically change the SQL statement when the selections or checkbox changed in First div.
Like: When the page loads, it should be like this:
$sql = Select * From events Where (every checkboxes are
checked and `All Stations` are selected.)
and when a user wants to filter the result from First div then the $sql statement should be changed to what the user selected and checked.
Like: I want to check the Events and Meetings checkbox with Main Station selection, so now i want that the $sql statement should be change to my selection in the Second div.
At first use parameterized query's, don't construct them dynamically. Examples and explanation on MSDN.
Write stored procedure that will receive value of selected option and will bring you data you need. F.e.:
CREATE PROCEDURE dbo.getevents
#value int
AS
SELECT *
FROM events
WHERE somecolumn = #value
It is simplified version, I guess you need some if statement like IF #value = 0...SELECT this ... IF #value = 1
In that case you can use:
$sql = "EXEC dbo.getevents ?";
$stmt = sqlsrv_query($conn, $sql, array($value));
And then fetch results and show it on your page.
EDIT#1
Using XAMP and SQL Server 2014
Disclaimer: I post this code only for demonstration purpose. Parameters are passed as a string, no styling, maybe some mistakes.
I have an installed XAMP. Downloaded sqlsrv libraries, enable them in php.ini.
I got local SQL Server with database Test. SQL server has an instance named sqldev. My computer name is workshop. So, instead of SERVER\INSTANCE should be workshop\sqldev. Instead of DATABASE - Test. That is what I wrote to connect.
At first I create table like this:
CREATE TABLE dummy (
id int identity(1,1),
[Desc] nvarchar(max),
[Type] nvarchar(100)
)
INSERT INTO dummy VALUES
('Do something already','Events'),
('Congrats!','Events'),
('Meet up at six PM','Meetings'),
('To Amsterdam','Travels'),
('goodbye!','Leaves')
Table contains some dummy-data to play with.
The next step:
Download jQuery from https://jquery.com/download/ (I used jquery-3.1.1.js)
index.php
<html>
<head>
<script src="jquery-3.1.1.js"></script>
<style>
table {
width:20%
}
table, td, th {
border-collapse: collapse;
border: 1px solid gray;
}
</style>
</head>
<body>
<div>Events Selection</div>
Events <input type="checkbox" id="option" class="options" name="options[]" value="Events">
Leaves <input type="checkbox" id="option" class="options" name="options[]" value="Leaves">
Meetings <input type="checkbox" id="option" class="options" name="options[]" value="Meetings">
Travels <input type="checkbox" id="option" class="options" name="options[]" value="Travels">
<div id="response"></div>
<script>
$('input:checkbox').click(function() {
$.ajax({
url: "sql_page.php",
type: "post",
data: $('.options:checked').serialize(),
success: function(data) {
$('#response').html(data);
}
});
});
</script>
</body>
</html>
sql_page.php
<?php
header('Content-Type: text/html; charset=utf-8');
$serverName = "SERVER\INSTANCE";
$connectionInfo = array("Database"=>"DATABASE");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if(isset($_POST['options'])) {
if( $conn === false ) {
echo "Unable to connect.</br>";
die( print_r( sqlsrv_errors(), true));
}
$values = $_POST['options'];
$valuelist = "'" . implode("', '", $values) . "'";
$tsql = "SELECT * FROM dummy WHERE [Type] IN (".$valuelist.");";
$stmt = sqlsrv_query($conn, $tsql);
if( $stmt === false ) {
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
echo "<table>";
while ($obj = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)) {
echo "<tr>
<td>".$obj[0]."</td>
<td>".$obj[1]."</td>
<td>".$obj[2]."</td>
</tr>\n";
}
echo "</table>";
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn );
}
?>
Then I go on index.php in my browser:
If you are using MySQL you need another libraries and commands to use, but they are similar to what I wrote. The main idea is to connect to the database and run some query with parameters, it is a sql_page.php idea.
The index.php part sends Ajax request to sql_page.php when checkboxes are clicked. And then show the data from this page (that was got from SQL Server) in div with id=response.
EDIT#2
Using EasyPHP Devserver 16.1.1 dowloaded from here
I installed EasyPHP in default folder, start it, went to http://127.0.0.1:1111, started Apache + PHP on port 8888, started MySQL.
I create a DB named air-hr, table named events in it. The script and structure of table below:
CREATE TABLE `events` (
`eventid` int(11) NOT NULL,
`eventname` varchar(100) NOT NULL,
`eventcategory` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `events` (`eventid`, `eventname`, `eventcategory`) VALUES
(1, 'Go now!', 'Leaves'),
(2, 'Meet some new people', 'Meetings'),
(3, 'Travel to Amsterdam', 'Travels'),
(4, 'PARTY HARD!', 'Events');
Also I create user test that can connect to DB and select from table.
I have created 2 files in C:\Program Files (x86)\EasyPHP-Devserver-16.1\eds-www project folder (their description is below) and copy jquery-3.1.1.js.
index.php like above and
sql_page.php
<?php
header('Content-Type: text/html; charset=utf-8');
if(isset($_POST['options'])) {
$values = $_POST['options'];
$valuelist = "'" . implode("', '", $values) . "'";
$query = "SELECT * FROM events WHERE eventcategory IN (".$valuelist.");";
$link = mysqli_connect("localhost", "test", "testpass", "air-hr");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
echo "<table>";
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_row($result)) {
echo "<tr>
<td>".$row[0]."</td>
<td>".$row[1]."</td>
<td>".$row[2]."</td>
</tr>\n";
}
mysqli_free_result($result);
}
echo "</table>";
mysqli_close($link);
}
?>
And results here:
Hope this helps you!
here you code
first named your inputs and select as follow:
<form action="sql_page.php" method="post">
<div>Events Selection</div>
Events <input type="checkbox" id="Option-1" name="Option-1" checked="true">
Leaves <input type="checkbox" id="Option-2" name="Option-2" checked="true">
Meetings <input type="checkbox" id="Option-3" name="Option-3" checked="true">
Travels <input type="checkbox" id="Option-4" name="Option-4" checked="true">
<div>Station Selection</div>
<select id="Filters1" name="Filters1">
<option value="0">All Stations</option>
<option value="1">Main Station</option>
<option value="2">Sub Station</option>
<option value="3">Sub Station Main Office</option>
</select>
<input type="submit" id="submit">
</form>
and in your sql_page.php here php code
if (isset($_POST)) {
foreach ($_POST as $col => $value) {
$whare .= "$col = '$value' AND ";
}
$whare = rtrim($whare,'AND ');
$sql = "Select * From events Where $whare";
}
I have an array of checkbox in a table in PHP file like this :
echo "<td $Blocked><input type =\"checkbox\" name=\"Blocked[]\" value=\"checkblock\" /></td>";
I am trying to get the value of number of checked checkboxes and save it to DB.
$Blocked = 'unchecked';
if ((isset($_POST['edit_tc']))) {
if (isset($_POST['Blocked'])) {
if (is_array($_POST['Blocked'])) {
foreach($_POST['Blocked'] as $value) {
error_log($value);
}
}
else {
$value = $_POST['Blocked'];
error_log($value);
}
$Blocked = 'checked';
}
}
"edit_tc" is the Submit button.
How do I take the number of it when the user checks the checkbox & clicks Submit button to save it to a table column?
I guess below code will solve all your problem.
<?php
$hello = array();
if(isset($_POST['submit'])) {
extract($_POST);
print_r($hello); //print all checked elements
}
?>
<form method="post">
<input type="checkbox" name="hello[]" value="1" <?php if(in_array(1, $hello)){ echo 'checked'; } ?>>
<input type="checkbox" name="hello[]" value="2" <?php if(in_array(2, $hello)){ echo 'checked'; } ?>>
<input type="checkbox" name="hello[]" value="3" <?php if(in_array(3, $hello)){ echo 'checked'; } ?>>
<input type="checkbox" name="hello[]" value="4" <?php if(in_array(4, $hello)){ echo 'checked'; } ?>>
<button type="submit" name="submit" value="Submit">Submit</button>
</form>
You have to check the value of each checkbox inside the checkbox array you are getting using in_arrayfunction of PHP.
If you need to understand whole thing, just let me know.
Will be glad to help you out.
Regards.
You can use this method...
if ((isset($_POST['edit_tc']))) {
if (isset($_POST['Blocked']))
{
$data = $_POST['Blocked'];
foreach ($data as $checkedValue)
{
$qry = mysql_query("INSERT INTO `Table_name` WHERE `column_id` = '$checkedValue'");
}
}
}
This is the method that will use to save each value as different records... You can modify that if needed.
You can simply use count() function to get total number of checkbox checked by user.
As only those checkbox values are posted to submitted page which are checked by user and if checkbox is not checked , its value will not be submitted. i.e The unchecked checkbox will not exist on submitted page.
USE:
$totalCheckboxChecked=count($_POST['Blocked']);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to validate my contact form using JavaScript but I dont know the validation codes and where to include,
I want validations should occur before redirecting to thank_you.php page
Plz help me...
HTML
<fieldset>
<?php include("formcode.php"); ?>
</fieldset>
formcode.php
<form method='post' action="database.php">
NAME: <input type='text' name='name' id='name' />
Email: <input type='text' name='email' id='email' />
Contact: <input type='text' name='contact' id='contact' />
Tour:
<select id="tour" name="tour" >
<option value="">--Select Tours--</option>
<option value="Tour1">Tour1</option>
<option value="Tour2">Tour2</option>
</select><br/>
Location:
<select id="location" name="location" >
<option value="">--Select Your Location--</option>
<option value="Loc1">Loc1</option>
<option value="Loc2">Loc2</option>
</select><br/>
Comment:<br />
<textarea name='comment' id='comment' /></textarea><br />
<input type='submit' value='Submit' />
</form>
database.php
<?php
if( $_POST )
{
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db_name", $con);
$users_name = $_POST['name'];
$users_email = $_POST['email'];
$users_contact = $_POST['contact'];
$users_tour = $_POST['tour'];
$users_location = $_POST['location'];
$users_comment = $_POST['comment'];
$users_name = mysql_real_escape_string($users_name);
$users_email = mysql_real_escape_string($users_email);
$users_contact = mysql_real_escape_string($users_contact);
$users_tour = mysql_real_escape_string($users_tour);
$users_location = mysql_real_escape_string($users_location);
$users_comment = mysql_real_escape_string($users_comment);
$query = "
INSERT INTO `db_name`.`dbtable` (`id`, `name`, `email`, `contact`, `tour`, `location`, `comment`, `timestamp`, `articleid`)
VALUES ( Null, '$users_name', '$users_email', '$users_contact', '$users_tour', '$users_location', '$users_comment', CURRENT_TIMESTAMP);";
mysql_query($query);
$url = 'thank_you.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
mysql_close($con);
include("mail.php");
}
?>
Perform the validation using javascript before submitting the form as shown below. First give id to your form so you can easily submit via JS
<form method='post' action="database.php" id='frm'></form>
make a call to validate function from the submit button like this
<input type='submit' value='Button' onclick=javacript:validate(); />
<script language=javascript> //easy one by one validation. this allow full control
function validate(){
if (document.getElementById('name').value==''){
alert('name is required');//customize this for your need. You may use div display
return;
}
//repeat the above for each form tags and values
document.getElementById('frm').submit();//submit the form
}
</script>
There are more advanced JQuery plugin for validation, the above is the simple primitive method
I'm building form with dynamic textboxes, if you click at the button "add", it appears a new textbox, i'm using php and javascript.
But i just can add into my database the value from the first textbox.
How can i insert multiple values into my database?
<html>
<head>
<title></title>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript"><!--
$(document).ready(function(){
var counter = 2;
$("#add").click(function () {
if(counter==11){
alert("Too many boxes");
return false;
}
$("#textBoxes").append("<div id='d"+counter+"' ><label for='t2'> Textbox "+counter+"</label><input type='textbox' id='t"+counter+"' > </div>\n");
++counter;
});
$("#remove").click(function () {
if(counter==1){
alert("No boxes");
return false;
}
--counter;
$("#d"+counter).remove();
});
});
// --></script>
</head>
<body>
<form method="POST">
<div id='textBoxes'>
<label for="t1"> Textbox 1</label>
<input name="nome" type='textbox' id='t1' ></div>
</div>
<input type='button' value='add' id='add'>
<input type='button' value='remove' id='remove'>
<input type='submit' name="adicionar" value='adicionar'>
</form>
<?php
$dbHost = 'localhost';
$dbUsername = 'hr';
$dbPassword = '';
$dbDatabase = 'r_inserir';
$db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");
if(isSet($_POST['adicionar']))
{
$nome=mysql_real_escape_string($_POST['nome']);
$sql= mysql_query("INSERT INTO registos(nome) values ('".$nome."')");
}
?>
</body>
</html>
Make the name like this in html:
<input name="nome[]" type='textbox' id='t1' ></div>
then in you javascript:
$("#textBoxes").append("<div id='d"+counter+"' ><label for='t2'> Textbox "+counter+"</label><input name='nome[]' type='textbox' id='t"+counter+"' > </div>\n");
these code return the array data into your php file. then insert it you your database.
if(isset($_POST['adicionar']))
{
//$nome=mysql_real_escape_string($_POST['nome']);
foreach($_POST['nome'] as $nome){
mysql_query("INSERT INTO registos(nome) values ('".mysql_real_escape_string($nome)."')");
}
//$sql= mysql_query("INSERT INTO registos(nome) values ('".$nome."')");
}
Important:
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
Firstly you must have dynamic names for the input fields along with ids, secondly loop through all the input values fetched from post and then save it.
e.g:
<input type='textbox' id='t"+counter+"' name='name"+counter+"' >
and then use $_POST['name'], $_POST['name1'] and so on to store it in database.
Not the best solution, but you can let the form send the text fields as an array:
<input type="text" name="nome[]" ... />
Then you can access this array in PHP using:
<?php
$_POST['nome'] //array containing all the values
?>
Finally, you can store this array serialized in the database. Have a look at http://www.php.net/manual/en/function.serialize.php
<?php
//when you store the data
$nome=mysql_real_escape_string( serialize ($_POST['nome']) );
//....
//when you retrieve the data
$nomes = unserialize($row['nome']); //(for example, returns array with all names)
?>
Important: When using serialized content, you might change the MySQL field type to TEXT instead of VARCHAR because it could be a very long string.
Appendix: You should also use mysqli instead of mysql!