PHP MYSQL Insert dynamic array into database - php

The dynamic HTML form (with some js help) and PHP script below insert user entered values into MySQL successfully, except that all rows from the form are placed in one row on the database. What am I doing wrong?
Dynamic form HTML:
<table id="dataTable" class="form" border="4">
<tbody style="font-size:8pt">
<th>
<td align="center">Company</td>
<td align="center">Project</td>
<td align="center">Sub-Project</td>
<td align="center">Change From</td>
<td align="center">Change To</td>
<td align="center">Activity</td>
<td align="center">Responsible</td>
<td align="center">Dur</td>
</th>
<tr >
<p>
<td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
<td><input style="width:100px" type="text" readonly="readonly" name="coa[]" value="<?php echo $co; ?>">
</td>
<td>
<select name="Projectname[]" style="font-size:10pt">
<option selected="selected" required="required">Select project</option>
<?php
foreach($proj as $item){
?>
<option value="<?php echo $item; ?>"><?php echo $item; ?></option>
<?php
}
mysqli_close($conn);
?>
</select>
</td>
<td><input style="width:100px" type="text" required="required" name="Subproj[]"></td>
<td><input style="width:130px" type="text" required="required" name="Changefrom[]"></td>
<td><input style="width:130px" type="text" required="required" name="Changeto[]"></td>
<td><input style="width:300px" type="text" required="required" name="Activity[]"></td>
<td><input style="width:90px" type="text" required="required" name="Resp[]"></td>
<td><input type="text" required="required" class="small" name="Durest[]"></td>
</p>
</tr>
</tbody>
</table>
PHP script:
<?php
include("../../db_conn_ci_i.php");
if(isset($_POST)==true && empty($_POST)==false){
$co=$_POST['co'];
$chkbox = $_POST['chk'];
$Projectname=$_POST['Projectname'];
$Subproj=$_POST['Subproj'];
$Changefrom=$_POST['Changefrom'];
$Changeto=$_POST['Changeto'];
$Activity=$_POST['Activity'];
$Resp=$_POST['Resp'];
$Durest=$_POST['Durest'];
}
$pco=implode(',',$co);
$pa=implode(',',$Projectname);
$pb=implode(',',$Subproj);
$c=implode(',',$Changefrom);
$d=implode(',',$Changeto);
$e=implode(',',$Activity);
$f=implode(',',$Resp);
$g=implode(',',$Durest);
$sql=" INSERT INTO projects (co,Projectname,Subproj,Changefrom,Changeto,Activity,Resp,Durest)
VALUES ('.$pco.','.$pa.','.$pb.','.$c.','.$d.','.$e.','.$f.','.$g.') ";
$query = mysqli_query($conn,$sql);
etc,etc
?>
Any advice?
Thank you.

You have added an extra column but not added a value for it. Since you are inserting seven columns with eight values, that's why it's not working for you. Your insert query is like below.
$sql=" INSERT INTO projects (Projectname,Subproj,Changefrom,Changeto,Activity,Resp,Durest)
VALUES ('.$pa.','.$pb.','.$c.','.$d.','.$e.','.$f.','.$g.') ";
$query = mysqli_query($conn,$sql);

Related

php - Inserted data was not saving in phpmyadmin database

I want to save my data in my phpmyadmin database.But it's not saving. So while saving my data, it refresh the page but data not showing in database
Here is my class by which i want to save data:
class User{
public function __construct(){
$host='localhost';
$user='root';
$password='';
$conn=mysql_connect($host,$user,$password);
if(!$conn){
die("Database Not Connected" . mysql_error());
}
mysql_select_db("db_sign_up");
echo "Database created! ";
}
public function save_user($data){
$sql="INSERT INTO tbl_user(first_name,last_name,email_address,password,mobile_number,address,
city_name,country_name,zip_code)
VALUES('$data[first_name]','$data[last_name]','$data[email_address]','$data[password]',
'$data[mobile_number]','$data[address]','$data[city_name]','$datacountry_name]','$data[zip_code]')";
if(!mysql_query($sql)){
die("sl Error". mysql_error());
}
echo "Saved Successfully!";
//mysql_close($conn);
}
}
here is UI
<?php
require_once './classes/user.php';
$obj=new User();
if(isset($_POST['btn'])){
$obj->save_user($_POST);
}
?>
<html>
<head><title> Database Basic</title></head>
<body>
<form action="sign_up.php" method="post">
<table border="1">
<tr><td>Personal Information</td><td></td></tr>
<tr>
<td> First Name</td>
<td>
<input type="name" name="first_name" value="<?php if(isset($_POST['first_number'])){ echo htmlentities($_POST['first_name']);} ?> "/>
</td>
</tr>
<tr>
<td> Last Name</td>
<td>
<input type="name" name="last_name" value="<?php if(isset($_POST['last_name'])){ echo htmlentities($_POST['last_name']);} ?> "/>
</td>
</tr>
<tr>
<td> Email Address</td>
<td>
<input type="name" name="email_address" value="<?php if(isset($_POST['email_address'])){ echo htmlentities($_POST['email_address']);} ?> "/>
</td>
</tr>
<tr>
<td> Password</td>
<td>
<input type="password" name="password" value="<?php if(isset($_POST['password'])){ echo htmlentities($_POST['password']);} ?> "/>
</td>
</tr>
<tr>
<td> Mobile Number</td>
<td>
<input type="name" name="mobile_number" value="<?php if(isset($_POST['mobile_number'])){ echo htmlentities($_POST['mobile_number']);} ?> "/>
</td>
</tr>
<tr>
<td> Address</td>
<td>
<textarea name="address" rows="4" cols="30"></textarea>
</td>
</tr>
<tr>
<td> City</td>
<td>
<input type="" name="city_name" value="<?php if(isset($_POST['city_name'])){ echo htmlentities($_POST['city_name']);} ?> "/>
</td>
</tr>
<tr>
<td> Country</td>
<td>
<select name="country_name">
<option value=" ">Select Country ...</option>
<option value="bangladesh">Bangladesh</option>
<option value="srilanka">Srilanka </option>
<option value="india">India</option>
</select>
</td>
</tr>
<tr>
<td> Zip Code</td>
<td>
<input type="name" name="zip_code" value="<?php if(isset($_POST['zip_code'])){ echo htmlentities($_POST['zip_code']);} ?> "/>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="btn" value="Save">
</td>
</tr>
</table>
</form>
</body>
You have an error in your INSERT STATEMENT:
you are using countryname variable in your query as:
'$datacountry_name]'
I think this should be like this:
'$data[country_name]'
Side note:
You are using mysql_ its deprecated I suggest you to use mysqli_ or PDO.
secondly your code is open for SQL Injection, you need to prevent with sql injection.
its function receives an array, then check your array. The type fields in the db, and if are properly filled.
field int type = int value
if it is returned as a string, you can convert this:
$string = $data[mobile_number];
$int = (int)$string; // convert string type for int.
or use the type varchar to the field
if not the case, say more about the your code.

Pass multiple values of same data field through POST

I'm trying to pass multiple values from same parameters of a form using POST, but can't figure out how to proceed. I've used bootstrap css such that I can add multiple products. And I want to process the data of multiple orders by passing the values using POST method.
On clicking 'Add another' link, additional set of data field appear which enables recording of multiple transactions of a same user.
The code is as follows:
<div class="col-xs-5 col-lg-offset-3">
<form action="billingProceed.php" method="post" role="form">
<table id="itemElement">
<tr>
<td>
<select class="form-control">
<option class="form-control"> Customer Name</option>
<option class="form-control"> Customer ID</option>
</select>
</td>
<td><input type="text" name="<?php echo $data["name"]; ?>" class="form-control" /></td>
</tr>
<tr>
<td>
<select class="form-control">
<option class="form-control"> Item Name</option>
<option class="form-control"> Item ID</option>
</select>
</td>
<td ><input type="text" name="<?php echo $data["item"]; ?>" class="form-control" /></td>
</tr>
<tr>
<td style="float:right;">Quantity
</td>
<td><input type="text" name="<?php echo $data["quantity"]; ?>" class="form-control" /></td>
</tr>
<tr>
<td style="float:right;">Price
</td>
<td><input type="text" name="<?php echo $data["price"]; ?>" class="form-control" /></td>
</tr>
<tr>
<td style="float:right;">Discount
</td>
<td><input type="text" name="<?php echo $data["discount"]; ?>" class="form-control" /></td>
</tr>
</table>
<input type="submit" value="Proceed" class="btn btn-primary" />
<p style="float:right;">Add another</p>
You can use an array name.
Example:
<input name="data['name'][1]">
<input name="data['name'][2]">
Firstly you should be aware of the name array, for input names.
HTML Example:
<form>
<a id="add_another" href="#">Add Another</a>
<table>
<tr class="product_item">
<td>
<input type="text" name="product[1][name]" value=""/>
</td>
<td>
<input type="text" name="product[1][item]" value=""/>
</td>
</tr>
<tr id="dummy">
<td>
<input type="text" name="product[0][name]" value=""/>
</td>
<td>
<input type="text" name="product[0][item]" value=""/>
</td>
</tr>
</table>
</form>
On POST, in your PHP script, you will access them as follows:
foreach($_POST['product'] as $product)
{
$name = $product['name'];
$item = $product['item'];
}
Shoot for the JS
//You'll always start with one product row.
var productCount = 1;
$('#add_another').click(function() {
var dummyproduct = $('#dummy').clone();
//Increment Product count
productCount += 1;
//Rename all inputs
dummyproduct.find('input[name^="product[0]"]').each(function(){
$(this).attr('name',$(this).attr('name').replace('product[0]','product['+productCount +']'));
});
//Remove Id from cloned dummy
dummyproduct.removeAttr('id').addClass('product_item');
//Insert row before Dummy
dummyproduct.insertBefore('#dummy');
});

How to Insert Multiple Checkboxes and their Textfields Into MySQL Database

I am new in the field of PHP.
I am working on a form to get information from a patient regarding a specific disease.
In this form i have multiple check-boxes and text fields with each check-box. If one check bos is checked then values of its text fields and checkbox values has to insert in database.
Please tell me the code to insert checked values along with textfields into database.
<form>
<table>
<tr>
<td colspan="4">Past Medical History:</td>
</tr>
<tr valign="top">
<td colspan="4" height="290"><table border="0" width="100%">
<tbody>
<tr>
<td width="26%"><div align="center">Problem</div></td>
<td width="18%"><div align="center">From (Year)</div></td>
<td width="56%"><div align="center">Details</div></td>
</tr>
<tr>
<td><input name="chkBP" id="chkBP" value="BP" type="checkbox" />
Blood Pressure</td>
<td><div align="center">
<input name="txtBPfrom" id="txtBPfrom" size="15" value="" type="text" />
</div></td>
<td><input name="txtBPDetail" id="txtBPDetail" size="40" value="" type="text" /></td>
</tr>
<tr>
<td><input name="chkDiabetes" id="chkDiabetes" value="Diabetes" type="checkbox" />
Diabetes</td>
<td><div align="center">
<input name="txtDiabetesfrom" id="txtDiabetesfrom" size="15" value="" type="text" />
</div></td>
<td><input name="txtDiabetesDetail" id="txtDiabetesDetail" size="40" value="" type="text" /></td>
</tr>
<tr>
<td><input name="chkHighCholes" id="chkHighCholes" value="HighCholesterol" type="checkbox" />
High Cholesterol</td>
<td><div align="center">
<input name="txtHighCholesfrom" id="txtHighCholesfrom" size="15" value="" type="text"/>
</div></td>
<td><input name="txtHighCholesDetail" id="txtHighCholesDetail" size="40" value="" type="text" /></td>
</tr>
<tr>
<td><input name="chkArthritis" id="chkArthritis" value="Arthritis" type="checkbox" />
Arthritis</td>
<td><div align="center">
<input name="txtArthritisfrom" id="txtArthritisfrom" size="15" value="" type="text" />
</div></td>
<td><input name="txtArthritisDetail" id="txtArthritisDetail" size="40" value="" type="text" /></td>
</tr>
<tr>
<td><input name="chkAsthma" id="chkAsthma" value="Asthma" type="checkbox" />
Asthma</td>
<td><div align="center">
<input name="txtAsthmafrom" id="txtAsthmafrom" size="15" value="" type="text" />
</div></td>
<td><input name="txtAsthmaDetail" id="txtAsthmaDetail" size="40" value="" type="text" /></td>
</tr>
<tr>
<td><input name="chkCirculation" id="chkCirculation" value="Circulation" type="checkbox" />
Circulation</td>
<td><div align="center">
<input name="txtCirculationfrom" id="txtCirculationfrom" size="15" value="" type="text" />
</div></td>
<td><input name="txtCirculationDetail" id="txtCirculationDetail" size="40" value="" type="text" /></td>
</tr>
</table></td>
</tr>
</form>
You will need to establish a connection to the database.
When the form is posted collect this data and insert into the database accordingly using $_POST.
Helpful example can be found here to connect
And to insert data
$link = mysqli_connect("localhost","root","","web_table");
mysqli_query($link,"INSERT INTO web_formitem (`ID`, `formID`, `caption`, `key`, `sortorder`, `type`, `enabled`, `mandatory`, `data`)
VALUES (105, 7, 'Tip izdelka (6)', 'producttype_6', 42, 5, 1, 0, 0)")
or die(mysqli_error($link));
first add any method attribute to your form tag like, get or post
<form>
to
<form action= "" method="post">
and add a submit button too in your form
now on submit your form will post your form value
and you can catch them by php as to insert in database
<?php
if(isset($_POST['submit_btn_name']))
{
//your database connect
//catch all value, for example
$val=$_POST['check_value'];
//your insert query
}
?>
A checkbox will only post when it's checked.
A textfield will always get posted even when it's empty.
Use a form:
<form name="contactform" method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
Add a submit button:
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
PHP:
<?php
//var_dump($_POST);
$chkBP = $_POST['chkBP'];
$txtBPfrom = $_POST['txtBPfrom'];
$txtBPDetail = $_POST['txtBPDetail'];
//echo "-- $txtBPfrom $txtBPDetail --";
if ($chkBP == "BP"){
//echo"Bloodpressure = checked";
$sql="INSERT INTO patient_details (from, detail)
VALUES ('$txtBPfrom', '$txtBPDetail')";
mysql_query($sql);
}else{
echo"Bloodpressure = not checked";
}
?>
Demo: here

php inserting last inserted values to the database

I have my login table in mysql is like this
id
fname
lname
email
contactno
userid
password
acctype
status
Now my form is like this
<form name="frm" method="post" action="registerform.php">
<table id="new-account" class="create-an-account" width="100%" border="1" cellspacing="10px" cellpadding="10px">
<tr>
<td width="45%">
<label for="firstname">First Name</label>
<input type="text" style="width:230px;" name="Firstname" id="Firstname" /></td>
<td width="10%"></td>
<td width="45%">
<label for="lastname">Last Name:</label>
<input type="text" style="width:230px;" name="LastName" id="LastName" />
</td>
</tr>
<tr>
<td>
<label for="">Account Type</label>
<select class="select" name="at" id="ValidSelection" style="width:245px;" >
<option value="0">Select Account Type</option>
<option value="agent">agent</option>
<option value="admin">admin</option>
</select>
</td>
</tr>
<tr>
<td><label for="">Email Id:</label></td>
</tr>
<tr>
<td><input type="text" name="email" id="ValidEmail" style="width:230px;"/></td>
</tr>
<tr>
<td><label for="">Contact Number</label></td>
</tr>
<tr>
<td><input type="text" name="contact" id="ValidNumber" style="width:230px" /></td>
</tr>
<tr>
<td><label for=""><strong>Choose Your Login Id:</strong></label>
<input type="text" style="width:230px;" name="LoginId" id="LoginId"/>
</td>
</tr>
<tr>
<td><label for=""><strong>Password: <br /></strong></label></td>
</tr>
<tr>
<td><input type="password" style="width:230px;" name="Password" id="ValidPassword" /></td>
</tr>
<tr>
<td><label for="">Confirm Password:</label></td>
</tr>
<tr>
<td>
<input type="password" style="width:230px;" name="ConfirmPassword" id="ValidConfirmPassword"
/>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="signup" value="Create Account" style="margin-top:20px" /></td>
</tr>
</table>
and for insert data my php code is like this
<?php
if(isset($_REQUEST['signup'])) {
mysql_query("insert into login (`fname`,`lname`,`email`,`contactno`,`userid`,`password`,`acctype`,`status`) values('".$_REQUEST['Firstname']."','".$_REQUEST['LastName']."','".$_REQUEST['email']."','".$_REQUEST['contact']."','".$_REQUEST['LoginId']."','".$pswd."','".$_REQUEST['at']."','active')");
}
?>
Now here when I am reloading the page it is automatically inserting the last entered values to the database. So here can someone kindly tell me what is the issue here? Any help and suggestions are welcome.
If you reload the page after submitting a form, it will keep the POST data. To solve this follow the below things :
You can redirect to some other page after inserting the data, use header("location:new_page.php")
You can unset REQUEST, use unset($_REQUEST) after insert
after inserting the $_POST data use redirect to avoid this situation .
even you can redirect to same page like this :-
header('Location: '.$_SERVER['PHP_SELF']);
exit;

How do i fetch data (table) from inner loop dependant upon outer loop?

I have two tables named tbl_collectiondesireddatetimelocations and tbl_locations
Structure of tbl_collectiondesireddatetimelocations is :
pk_collectiondesireddatetimelocationid
, fk_tbl_locations_locationid, fromdate, todate, fromtime, totime
And structure of tbl_locations is
pk_locationid, name
I have following page:
In the first column location is populated from tbl_locations table.
What i want is to fill the data for the requested column? Data will be retrieved from the tbl_collectiondesireddatetimelocations. For e.g. location id of bangalore is 1. I will check if there is a location id 1 in the tbl_collectiondesireddatetimelocations fk_tbl_locations_locationid column. If it exists it will retrieve the fromdate,todate,fromtime,totime column values and fill that data for that particular location.
I have written following code :
<table style="width:100%;margin:0px;" class="maintable">
<tr><td colspan="1"></td><td colspan="4">
<font style="font-weight:bold;">Requested</font></td>
<td colspan="4"><font style="font-weight:bold;">Assigned</font></td>
</tr><tr>
<td>Location</td>
<td>From Date</td>
<td>To Date</td>
<td>From Time</td>
<td>To Time</td>
<td>From Date/td>
<td>To Date</td>
<td>From Time</td>
<td>To Time</td></tr>
<?php
foreach($locations as $location)
{
foreach($desireddatetimelocations as $desireddatetimelocation)
{
if($desireddatetimelocation['fk_tbl_locations_locationid']==
$location['pk_locationid'])
{
$fromdate=$desireddatetimelocation['fromdate'];
$todate=$desireddatetimelocation['todate'];
$fromtime=$desireddatetimelocation['fromtime'];
$totime=$desireddatetimelocation['totime'];
}
}
?>
<tr><td><?php echo $location['name'];?></td>
<td><input type="text" name="txtFromDate_
<?php echo $location['pk_locationid'];?>" class="field" style="width:80px;"
readonly="" value="<?php echo $fromdate;?>"/></td>
<td><input type="text" name="txtToDate_
<?php echo $location['pk_locationid'];?>"
class="field" style="width:80px;" readonly="" value="<?php echo $todate;?>"/></td>
<td><input type="text" name="txtFromTime_
<?php echo $location['pk_locationid'];?>"
class="field" style="width:80px;" readonly="" value="<?php echo $fromtime;?>"/></td>
<td><input type="text" name="txtToTime_
<?php echo $location['pk_locationid'];?>"
class="field" style="width:80px;" readonly="" value="<?php echo $totime;?>"/></td>
<td><input type="text" name="txtAssignedFromDate_
<?php echo $location['pk_locationid'];?>"
class="date-pick field" style="width:80px;"/></td>
<td><input type="text" name="txtAssignedToDate_
<?php echo $location['pk_locationid'];?>"
class="date-pick field" style="width:80px;"/></td>
<td><input type="text" name="txtAssignedFromTime_
<?php echo $location['pk_locationid'];?>"
class="time-pick field" style="width:80px;" /></td>
<td><input type="text" name="txtAssignedToTime_
<?php echo $location['pk_locationid'];?>"
class="time-pick field" style="width:80px;"/></td></tr>
<?php
}
?>
</table>
Ideally data should be displayed for bangalore and chennai location as table tbl_collectiondesireddatetimelocations contains data for these locations. But i am getting wrong result:Data is repeated for other locations also
Wrong output:
I am confused where I am getting this wrong?
The problem is, that the variables $fromdate, $todate, aso. are still set in the second run even if no location found.
As a quick fix you can just reset them before the inner loop:
foreach($locations as $location)
{
$fromdate='';
$todate='';
$fromtime='';
$totime='';
foreach($desireddatetimelocations as $desireddatetimelocation)
{
Another approach would be to create an associative array of the location=>date/time mapping and use that in the loop:
<?php
$dateTimes = array();
foreach($desireddatetimelocations as $desireddatetimelocation)
{
$dateTimes[$desireddatetimelocation['fk_tbl_locations_locationid']] =
$desireddatetimelocation;
}
foreach($locations as $location)
{
?>
<tr>
<td><?php echo $location['name'];?></td>
<td>
<input type="text" name="txtFromDate_<?php echo $location['pk_locationid'];?>"
class="field" style="width:80px;" readonly=""
value="<?php echo isset($dateTimes[$location['pk_locationid']]) ?
$dateTimes[$location['pk_locationid']]['fromdate'] : '';?>"/>
</td>
.....

Categories