I want to add dynamic form fields in the database using PHP. I have used angular to add dynamic form fields. The thing is when I am trying to insert this data into the database only last form field is inserting in the database. SO, I used array and loop to increment and update this form field into the database. but somehow query is not working properly and data is also not inserting into the database. can anybody tell me what is wrong here? I am stuck. Please help. Thanx in advance
Php Code:
<?php
if(isset($_POST['submit_row']))
{
$link = mysqli_connect("localhost", "root", "", "midata");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$camp_name = mysqli_real_escape_string($link, $_REQUEST['camp_name']);
$start_date = mysqli_real_escape_string($link, $_REQUEST['start_date']);
$end_date = mysqli_real_escape_string($link, $_REQUEST['end_date']);
$store = mysqli_real_escape_string($link, $_REQUEST['$store']);
$elements= $mysqli->real_escape_string($_POST['elements']);
$quantity = $mysqli->real_escape_string($_POST['quantity']);
$description = mysqli_real_escape_string($link, $_REQUEST['description']);
for($i=0;$i<count($elements);$i++)
{
if( $elements[$i]!="" && $quantity[$i]!="")
{
$sql = "INSERT INTO create_campaign(camp_name, start_date, end_date,store,elements,quantity, description )
VALUES('$camp_name',' $start_date', '$end_date','$store','$elements[$i]', '$quantity[$i]', '$description')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_query($sql, $link);
}
}
}
?>
HTML Code:
<div class="row col-md-12" ng-app="angularjs-starter" ng-controller="MainCtrl">
<fieldset data-ng-repeat="choice in choices" name="records">
<label for="inputPassword3" class="col-md-1 control-label">Elements</label>
<div class="form-group col-md-3 ">
<input type="text" placeholder="Campaign Name" ng-model="choice.name" class="form-control c-square c-theme input-lg" name="elements[]">
</div>
<label for="inputPassword3" class="col-md-1 control-label">Quantity</label>
<div class="form-group col-md-3" >
<select class="form-control c-square c-border-2px c-theme" name="quantity[]>
<option value="1">100</option>
<option value="2">200</option>
<option value="3">300</option>
<option value="4">400</option>
</select>
</div>
<button type="button" class="btn c-theme-btn c-btn-uppercase btn-lg c-btn-bold c-btn-square" ng-click="addNewChoice()" >add</button>
<button ng-show="$last" ng-click="removeChoice()" class="btn c-theme-btn c-btn-uppercase btn-lg c-btn-bold c-btn-square" >Remove</button>
</fieldset>
</div>
</div>
</div>
<div class="form-group">
<input type="text" placeholder="Description" class="form-control c-square c-theme input-lg" name="description">
</div>
<input class="btn c-theme-btn c-btn-uppercase btn-lg c-btn-bold c-btn-square" value="Submit" type="submit" name="submit_row">
</form>
</div>
You should declare a variable like x=1 and use it inside your array of input like name="input_name[+ x +]"
and increment the variable after each input field i.e x++
You can access those inputs using inputName[1], input_name[2] in your php controller
Related
I'm trying to insert data to MySQL with a form that is in a Bootstrap modal but it doesn't work.
I don't know why but my form method is POST and it seems to be a GET because it prints the data in the web address.
When I try to insert the data through a basic form with the same php code (no format, simple as hell) it inserts the data.
Here's my form in the bootstrap modal.
<div class="container 2">
<button type="button" class="btn btn-primary btn-lg btn-block" data-toggle="modal" data-target="#newRoute">
CREAR NUEVA RUTA
</button>
<div class="modal fade" id="newRoute" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-md" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<form class="route" method="post">
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="form-group">
<label for="name">Ponle un nombre a la ruta</label>
<input type="text" class="form-control" id="name" name="name" required>
</div>
<div class="form-group">
<label for="city">Ciudad</label>
<input type="text" class="form-control" id="city" name="city" required>
</div>
<div class="form-group">
<label for="length">Distancia</label>
<input type="text" class="form-control" id="length" name="length" required>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="form-group">
<label for="start_point">Punto de salida</label>
<input type="text" class="form-control" id="start_point" name="start_point"
required>
</div>
<div class="form-group">
<label for="difficulty">Dificultad</label>
<input type="text" class="form-control" id="difficulty" name="difficulty"
required>
</div>
<div class="form-group">
<label for="date">Fecha de la ruta</label>
<input type="date" class="form-control" id="date" name="date" required>
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="form-group">
<label for="description">Detalles de la ruta</label>
<textarea class="form-control" rows="5" id="description"
name="description"></textarea>
</div>
</div>
<div class="modal-footer">
<div class="form-group">
<button type="submit" name="submit" id="submit" class="btn btn-primary"
value="Enviar">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
and here is my PHP code
include('db/db.php');
if(isset($_POST['submit'])) {
// Adjudicar name a variable
$name = stripslashes($_POST['name']);
$name = mysqli_real_escape_string($conn, $name);
// Adjudicar city a variable
$city = stripslashes($_POST['city']);
$city = mysqli_real_escape_string($conn, $city);
// Adjudicar length a variable
$length = stripslashes($_POST['length']);
$length = mysqli_real_escape_string($conn, $length);
// Adjudicar start_point a variable
$start_point = stripslashes($_POST['start_point']);
$start_point = mysqli_real_escape_string($conn, $start_point);
// Adjudicar difficulty a variable
$difficulty = stripslashes($_POST['difficulty']);
$difficulty = mysqli_real_escape_string($conn, $difficulty);
// Adjudicar date a variable
$date = stripslashes($_POST['date']);
$date = mysqli_real_escape_string($conn, $date);
// Adjudicar description a variable
$description = stripslashes($_POST['description']);
$description = mysqli_real_escape_string($conn, $description);
// QUERY
$query = "INSERT INTO routes (name, city, length, start_point, difficulty, user_id, date, description) VALUES ('$name','$city',$length,'$start_point','$difficulty',".$_SESSION['id'].",'$date','$description')";
// Se realiza la query
$result = mysqli_query($conn,$query);
//CondiciĆ³n si se realiza la query correctamente
if($result){
header("Location: routes.php");
echo '<script type="text/javascript">alert("'.$query.'");</script>';
}else{
echo '<script>alert("ERROR");</script>';
}}
my db.php (connection to database)
$conn = new mysqli('localhost', 'root', "", 'users');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Thanks in advance!
PS. When I submit the form, this is what appears in the address (all the fields were filled by sample text). It seems to be a get form.
http://localhost/Proyecto/routes.php?name=Test&city=Test&length=20&start_point=Test&difficulty=Test&date=2018-05-12&description=Test+description&submit=Enviar
Try to check if you have forget to close any other form somewhere on your code that should be with method="get" or without method attribute
and so when you submit the data it gets the method from that form.
The code you have publish here should work correctly.
Your form code is correct, I have checked it on my system. You must be checking/testing some other page or form.
how do I foreach through html input form and insert multiple rows or one based on a selected date field? in other words when a user enters "name" "description" and "shift" and then selects either one date or more then one. PHP will then enter the same information for either one new row or multiples based on how many dates were selected.
<?php
if(isset($_REQUEST['submit']))
{
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "xxxx", "xxxx", "xxxx");
// Check connection
if($link === false){
die("| ERROR: Could not connect. " . mysqli_connect_error());
}
$name = mysqli_real_escape_string($link, $_REQUEST['name']);
$desc = mysqli_real_escape_string($link, $_REQUEST['description']);
$shift = mysqli_real_escape_string($link, $_REQUEST['shift']);
$date = mysqli_real_escape_string($link, $_REQUEST['daterange']);
$sql = "insert into db (name,description,shift,evdate) values ('$name', ' $desc','$shift','$date')";
$sql2 = "insert into db (name,description,shift,evdate) values ('$name', ' '$desc','$shift','$insert')";
if ($date=0) {
$result = mysqli_query($link, $sql);
}else{
$daterange = explode(',',$date);
foreach($daterange as $insert) {
$result = mysqli_query($link, $sql2);
}
}
if(mysqli_query($link, $sql)){
echo "";
} else{
echo "| ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
if ($link->multi_query($sql) === TRUE) {
echo "It Worked..... Maybe!!!!!!";
} else {
echo "Error: " . $sql . "<br>" . $link->error;
}
}
$link->close();
?>
<form action="test_insert.php" method="post">
<div class="col col-lg-2 col-lg-offset-0">
<div class="form-group col-lg-offset-0 col-lg-12">
<label for="Name">Employee Name:</label>
<input type="text" name="name" placeholder="First & Last Name" id="name" required>
<p class="help-block col-lg-12">First and Last Name Please.</p>
</div>
</div>
<div class="col col-lg-offset-0 col-lg-2">
<div class="form-group col-lg-12">
<label for="description">Description:</label>
<input type="text" name="description" id="description" placeholder="description..." required>
<p class="help-block">For Example: "Vacation Full Day" or "PTO 2 Hours." </p>
</div>
</div>
<div class="col col-lg-offset-0 col-lg-3">
<label for="shift">Shift:</label><br>
<input type="radio" name="shift" value="First Shift" id="shift" checked> First Shift |
<input type="radio" name="shift" value="Second Shift" id="shift"> Second Shift |
<input type="radio" name="shift" value="Third Shift" id="shift"> Third Shift
<p class="help-block">Select Correct Shift Worked.</p>
</div>
<div class="col col-lg-offset-0 col-lg-3">
<div class="form-group col-lg-10">
<label for="date2">Date/Dates:</label>
<input type="text" id="datepicker1" name="daterange" placeholder="Select Your Date" />
</div>
<div class="form-group col-lg-10">
<label for="date2">Date/Dates:</label>
<input type="text" id="datepicker2" name="daterange" placeholder="Select Your Date" />
</div>
<div class="form-group col-lg-10">
<label for="date2">Date/Dates:</label>
<input type="text" id="datepicker3" name="daterange" placeholder="Select Your Date" />
</div>
<div class="form-group col-lg-10">
<label for="date2">Date/Dates:</label>
<input type="text" id="datepicker4" name="daterange" placeholder="Select Your Date" />
</div>
<div class="form-group col-lg-10">
<label for="date2">Date/Dates:</label>
<input type="text" id="datepicker5" name="daterange" placeholder="Select Your Date" />
</div>
<div class="form-group col-lg-6">
<input type="submit" name="submit" class= "btn btn-primary">
</div>
</div>
</div>
</form>
Think the best way is to use AJAX,
Then with the response as a string you make a table or foreach in php as a string and then use the .html adapter to output the newly made data.
function submitForm(form){
var url = form.attr("action");
var formData = {};
$(form).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$.post(url, formData).done(function (data) {
$('#showresults').html(result);
});
}
**I want to edit data in my table using modal but i can only call ID=1 i cant edit the others and also i need to refresh my web before i can see the changes?
// my update code
<?php
$id= "1";
$mysqli = new mysqli('127.0.0.1','root','','books');
$query = $mysqli->query("select * from bookrecords where ID='$id' ");
$row = $query->fetch_assoc();
if(isset($_POST['update'])) {
$id = $_POST['id'];
$nm = $_POST['nm'];
$is = $_POST['is'];
$pb = $_POST['pb'];
$au = $_POST['au'];
$result = $mysqli->query("UPDATE bookrecords set BookName='$nm', ISBN='$is', Publisher='$pb', Author='$au' where ID='$id'");
if($result){
?>
<div class="alert-success" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="close"><span aria-hidden="true">×</span></button>
<strong>Success!</strong> your data has been updated.
</div>
<?php
} else{
?>
<div class="alert-failed" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="close"><span aria-hidden="true">×</span></button>
<strong>Failed!</strong> Error updating. Try Again!
</div>
<?php
}
}
?>
** and this is my Modal form....
<div class="form-group">
<label for="id">ID:</label>
<input type="text" class="form-control" id="id" name="id" value="<?php echo $row['ID']?>" readonly>
</div>
<div class="form-group">
<label for="nm">BookName:</label>
<input type="text" class="form-control" id="nm" name="nm" value="<?php echo $row['BookName']?>">
</div>
<div class="form-group">
<label for="is">ISBN:</label>
<input type="text" class="form-control" id="is" name="is" value="<?php echo $row['ISBN']?>">
</div>
<div class="form-group">
<label for="pb">Publisher:</label>
<input type="text" class="form-control" id="pb" name="pb" value="<?php echo $row['Publisher']?>">
</div>
<div class="form-group">
<label for="au">Author:</label>
<input type="text" class="form-control" id="au" name="au" value="<?php echo $row['Author']?>">
</div>
<button type="submit" name="update" class="btn-primary">Update</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</form>
</div>
<div class="modal-footer">
</div>
</div>
**so how can i call any of my item/data in table? Please help me.
Your HTML form must have a hidden field with the id of book record, which will be send to the PHP script when pressing the "Update" button. The hidden field should look like this:
<input type="hidden" name="bookrecordId" value="ID_OF_BOOKRECORD_HERE" />
You can access the value of the transfered id with $_POST['bookrecordId'] in your receiving PHP script. Use it to build one or two prepared statements which will check if the row exists and then run an UPDATE query to update the values.
Submit button does not functioning when I click. All of the code seem to have no errors, but it just does not inserted to my database. I am currently using bootstrap. I don't know what is the error I am having.
index.html
<div class="container">
<div class="col-md-5">
<div class="form-area">
<form role="form">
<br style="clear:both">
<h3 style="margin-bottom: 25px; text-align: center;">Schedule Form</h3>
<form name="form2" method="post" action="scheduleform.php">
<div class="form-group">
<input type="text" class="form-control" id="tajuk" name="tajuk" placeholder="Tajuk" required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="tarikh" name="tarikh" placeholder="Tarikh" required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="mobile" name="mobile" placeholder="Mobile Number" required>
</div>
<div class="form-group">
<textarea class="form-control" type="textarea" id="maklumat" name="maklumat" placeholder="Maklumat" maxlength="140" rows="7"></textarea>
<span class="help-block"><p id="characterLeft" class="help-block ">You have reached the limit</p></span>
</div>
<button><input type="submit" name="submit" class="btn btn-primary pull-right">Submit Form</button>
</form></form>
</div>
</div>
</div>
<!-- /#page-content-wrapper -->
scheduleform.php
<?php
$server = "localhost";
$user = "root";
$pass = "";
$dbname = "kajangdb";
//Creating connection for mysqli
$conn = new mysqli($server, $user, $pass, $dbname);
//Checking connection
if($conn->connect_error){
die("Connection failed:" . $conn->connect_error);
}
$tajuk = mysqli_real_escape_string($conn, $_POST['tajuk']);
$tarikh = mysqli_real_escape_string($conn, $_POST['tarikh']);
$mobile = mysqli_real_escape_string($conn, $_POST['mobile']);
$maklumat = mysqli_real_escape_string($conn, $_POST['maklumat']);
$sql = "INSERT INTO schedule (tajuk, tarikh, mobile, maklumat) VALUES ('$tajuk', '$tarikh', '$mobile', '$maklumat')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Issues i found with your code.
1. You don't need to wrap form element with another form element
2.
$sql = "INSERT INTO schedule (tajuk, tarikh, mobile, maklumat) VALUES ('$tajuk', '$tarikh', '$mobile', '$maklumat')";
Here you added extra space after "schedule" and "VALUES" which may created problem. change your code as below.
$sql = "INSERT INTO schedule(tajuk, tarikh, mobile, maklumat) VALUES('$tajuk', '$tarikh', '$mobile', '$maklumat')";
1) Nested forms are definitely error-prone. Use more forms in a page, if
you wish, but never nest them. Here you are using form2 inside
another one. Don't do that, delete the outer one.
2) Your submit button syntax is wrong. Use input OR button.
Instead of:
<button><input type="submit" name="submit" class="btn btn-primary pull-right">Submit Form</button>
use:
<input type="submit" name="submit" value="Submit Form" class="btn btn-primary pull-right" />
or:
<button type="submit" name="submit" class="btn btn-primary pull-right">Submit Form</button>
3) Provide validation on $_POST values. Like:
if (
!isset($_POST['tajuk']) ||
!isset($_POST['tarikh']) ||
!isset($_POST['mobile']) ||
!isset($_POST['maklumat'])
) {
echo 'Error: not all values are valid. Please provide valid values.';
}
$conn = new mysqli($server, $user, $pass, $dbname);
//...
I recommend you to always prepare your sql statements for execution, in order to avoid the SQL injection risks. Use prepare() before querying. See: mysqli::prepare.
Also use exception handling. See please The mysqli_sql_exception class
EDIT 1:
It is not allowed to use paragraphs (<p>) inside spans (<span>). Use other container types, like <div> instead of <span>. So, replace
<span class="help-block">
<p id="characterLeft" class="help-block ">
You have reached the limit
</p>
</span>
with
<div class="help-block">
<p id="characterLeft" class="help-block ">
You have reached the limit
</p>
</div>
here i am trying to upload image to directory and add the path in database.
here i am first adding some product details and trying to upload the image to uploads directory and add the uploaded image path in database.
here is what i have done:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "wan_products_box");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$product_name = mysqli_real_escape_string($link, $_POST['product_name']);
$product_category = mysqli_real_escape_string($link, $_POST['product_category']);
$product_price = mysqli_real_escape_string($link, $_POST['product_price']);
$pro_url = mysqli_real_escape_string($link, $_POST['pro_url']);
$co_owners = mysqli_real_escape_string($link, $_POST['co_owners']);
// attempt insert query execution
$sql = "INSERT INTO product_list (product_name, product_category, product_price,product_referrence_URL,product_co_owners) VALUES ('$product_name', '$product_category', '$product_price', '$pro_url', '$co_owners')";
if(mysqli_query($link, $sql)){
echo "New product created.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
//image upload code
if($_POST)
{
if($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
if(file_exists("uploaded_images/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
if(move_uploaded_file($_FILES["file"]["tmp_name"],"uploaded_images/" . $_FILES["file"]["name"]))
{
$query_image = "INSERT INTO product_list (product_image_url) values ('".$_FILES['file']['name']."')";
if(mysql_query($query_image))
{
echo "Stored in: " . "uploaded_images/" . $_FILES["file"]["name"];
}
else
{
echo 'Unable to store';
}
}
}
}
}
mysqli_close($link);
?>
this is my html form:
<div id="menu2" class="tab-pane fade">
<h4>Add new product</h4>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="panel panel-default">
<div class="panel-body">
<form class="form-horizontal" method="post" action="files/insert.php" role="form">
<div class="form-group">
<label class="control-label col-sm-2" for="product_name">Product Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="product_name" id="product_name" placeholder="Iphone 5c" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Product Category</label>
<div class="col-sm-10">
<select class="btn-btn-primary form-control" name="product_category">
<option>Mobile</option>
<option>Television</option>
<option>Printer</option>
<option>Watch</option>
<option>Monitor</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="product-pic">Upload your profile picture</label>
<div class="col-sm-10">
<input type="file" class="form-control" name="file" id="file" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="product_price">Product Price</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="product_price" id="product_price" placeholder="Rs.36,000" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="pro_url">Reference URL</label>
<div class="col-sm-10">
<input type="URL" class="form-control" name="pro_url" id="pro_url" placeholder="http://www.amazon.com" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="co_owners">Co-owners</label>
<div class="col-sm-10">
<select class="btn-btn-primary form-control" name="co_owners">
<option>Select no. owners</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
<option>11</option>
<option>12</option>
<option>13</option>
<option>14</option>
<option>15</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Add product</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
the data is inserted to database but the image upload part is not happening...
how can i do this? how can i modify the code to upload the image to database and add path to database?
when i run this the output i get is
New product created.
Notice: Undefined index: file in D:\xampp\htdocs\wan\files\insert.php on line 31
Notice: Undefined index: file in D:\xampp\htdocs\wan\files\insert.php on line 37
Notice: Undefined index: file in D:\xampp\htdocs\wan\files\insert.php on line 43
Notice: Undefined index: file in D:\xampp\htdocs\wan\files\insert.php on line
There are a few things wrong in your code.
Firstly, your form is missing a valid enctype enctype="multipart/form-data" it is required when dealing with files.
http://php.net/manual/en/features.file-upload.post-method.php
You're also mixing MySQL APIs in your second query.
$query_image = "INSERT INTO product_list (product_image_url) values ('".$_FILES['file']['name']."')";
if(mysql_query($query_image))
So it will fail.
Use the same method you used in your first query.
Those different APIs do not intermix.
So change that to if(mysqli_query($link, $query_image))
Also add or die(mysqli_error($link)) to mysqli_query() to check for errors.
Also make sure the folder has proper permissions to be written to.
Another thing, your <select>'s options have no values
<option>Select no. owners</option>
<option>1</option>
...
You need to add those
<option value="empty_value">Select no. owners</option>
<option value="1">1</option>
...
and do the same for the others.
Same thing for <option>Mobile</option>. There should be values for those too.
<option value="mobile">Mobile</option>
...
You will not get anything entered in your database for those.
Apart from the problems in HTML part like the lack of enctype="multipart/form-data". There is a problem in your second Query and this is the cause of these errors:
$query_image = "INSERT INTO product_list (product_image_url) values ('".$_FILES['file']['name']."')";
You need to change this to an UPDATE query and update the already created row in database.
Also it is a better approach to use the row's index number for the image name.