null column in protection from sql injection - php

hi i am having a contact form in my website where user can optionaly fill some of the fields and after click on submit button data save in to the database all of this worked fine until i decide to sanitize my code from sql injection as i mentioned at first before trying to sanitize it from sql injection it worked properly as i showed in below code
<form method="Post" action="">
<input type="text" name="name" />name
<select dir="rtl" style="width: 173px;" name="case" >
<option value="" disabled selected hidden>اplease choose</option>
<option value='rent'>rent</option>
<option value='sell'>sell</option>
</select >
<input type="checkbox" name="check1" value='a'>apartment<br>
<input type="submit" value="submit" />
</form>
<?php
include("config.php");
if(isset($_POST['submit'])){
$date_clicked = date('Y-m-d H:i:s');
}
//insert to database
$insert =mysqli_query($connect,"INSERT INTO $db_table VALUES (to simplify code i do not write this part)");
}
?>
now i have to fill all the dropdown lists and checkboxes otherwise it gives error "column '' can not be null". also i can not insert date and time into database it gives the same error. here is my code when i protect it fron sql injection:
<form method="Post" action="">
<input type="text" name="name" />name
<select dir="rtl" style="width: 173px;" name="case" >
<option value="" disabled selected hidden>اplease choose</option>
<option value='rent'>rent</option>
<option value='sell'>sell</option>
</select >
<input type="checkbox" name="check1" value='a'>apartment<br>
<input type="submit" value="submit" />
</form>
<?php
include("config.php");
if(isset($_POST['submit'])){
$date_clicked = date('Y-m-d H:i:s');
}
if(isset($_POST['submit'])){
//insert to database
$query = mysqli_prepare($connect, "INSERT INTO $db_table VALUES (?,?,?,?)");
/* bind parameters for markers */
mysqli_stmt_bind_param( $query, "ssss", $_POST[name],$_POST['check1'],$_POST['case'],$_POST['date_clicked']);
// execute query
if ( mysqli_stmt_execute($query) ) {
echo "Successfully inserted " . mysqli_affected_rows($connect) . " row";
} else {
echo "Error occurred: " . mysqli_error($connect);
}
}
?>
please help me

Make sure that your variables exist. This is necessary because your checkbox, for example, will be null if not checked and that could be a problem for the table you are using. You could set defaults and then insert it.
$name = !empty($_POST['name']) ? $_POST['name'] : '';
$check1 = !empty($_POST['check1']) ? $_POST['check1'] : '';
$case = !empty($_POST['case']) ? $_POST['case'] : '';
$date_clicked = date('Y-m-d H:i:s');
// prepare and bind
$stmt = $connect->prepare("INSERT INTO `$db_table` (`name`, `check1`, `case`, `date_clicked`) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $name, $check1, $case, $date_clicked);
$stmt->execute();
$stmt->close();

Related

Inserting Data into MySQL table using HTML form

I am currently trying to insert rows into a MySQL database, and most of the code is there but I'm having a few issues I can't diagnose. I know the database connection is good, and every time the submit button is pressed it runs the correct php script. The issue I'm having is that it always adds 2 records to the database table and fails to carry though any of the form data (it inserts two completely blank rows.)
Here's the code for the form (with a little extra code for the wordpress page)
<div class="main-container">
<div class="content-area">
<div class="middle-align">
<div class="site-main" id="sitefull">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<div>
<form method="POST" name="cutting tool" action="add-tool-script.php">
<table style="width:auto;">
<tr>
<th width="50%"><h2><ul>Tool Information</ul></h2><br></th>
<th width="50%"><ul><h2>Storage Information</h2></ul><br></th>
</tr>
<tr>
<td width="50%">
<h3>Tooling Name</h3><br>
<input type="text" name="name" placeholder="e.g. ShearHog"><br><br>
<h3>Tooling Type</h3><br>
<select name="type">
<option selected disabled hidden style='display: none' value=''></option>
<option value="Ballnose Endmill">Ballnose Endmill</option>
<option value="Bullnose Endmill">Bullnose Endmill</option>
<option value="Boring Bar">Boring Bar</option>
<option value="Brush">Brush</option>
<option value="Burnishing">Burnishing</option>
<option value="Chamfer Mill">Chamfer Mill</option>
<option value="Countersink">Countersink</option>
<option value="Drill">Drill</option>
<option value="Drill/Mill">Drill/Mill</option>
<option value="Engraver">Engraver</option>
<option value="Face Mill">Face Mill</option>
<option value="Flat Endmill">Flat Endmill</option>
<option value="High Feed Mill">High Feed Mill</option>
<option value="Reamer">Reamer</option>
<option value="Slitting Saw">Slitting Saw</option>
<option value="Spot Drill">Spot Drill</option>
<option value="Tap">Tap</option>
<option value="Threadmill">Threadmill</option>
<option value="Woodruff">Woodruff</option>
<option value="Other">Other</option>
</select><br><br>
<h3>Tooling Brand</h3><br>
<input type="text" name="brand" placeholder="e.g. Lakeshore Carbide"><br><br>
<h3>Part Number</h3><br>
<input type="text" name="part_number" placeholder="e.g. 360014X"><br><br>
<h3>Price</h3><br>
<input type="text" name="price" placeholder="e.g. 24.95"><br><br>
<h3>Overall Length</h3><br>
<input type="text" name="oal" placeholder="e.g. 2.5"><br><br>
<h3>Tooling Material</h3><br>
<select name="material">
<option selected disabled hidden style='display: none' value=''></option>
<option value="Carbide">Carbide</option>
<option value="Ceramic">Ceramic</option>
<option value="Diamond">Diamond</option>
<option value="HSS">HSS</option>
<option value="Powdered Metal">Powdered Metal</option>
</select><br><br>
<h3>Cutting Diameter</h3><br>
<input type="text" name="cutting_diam" placeholder="e.g. 0.250"><br><br>
<h3>Shank Diameter</h3><br>
<input type="text" name="shank_diam" placeholder="e.g. .250"><br><br>
<h3>Number of Flutes</h3><br>
<input type="text" name="flutes" placeholder="e.g. 3"><br><br>
<h3>Length of Cut (Flute Length)</h3><br>
<input type="text" name="loc" placeholder="e.g. .750"><br><br>
<h3>Corner Radius</h3><br>
<input type="text" name="corner_rad" placeholder="e.g. .004"><br><br>
</td>
<td width="50%">
<h3>Quantity in Stock</h3><br>
<input type="text" name="qty" placeholder="e.g. 37"><br><br>
<h3>Minimum Trigger Quantity</h3><br>
<input type="text" name="trigger_qty" placeholder="e.g. 4"><br><br>
<h3>Reorder Link</h3><br>
<input type="text" name="reorder_link" placeholder="e.g. example.com"><br><br>
<h3>Toolbox Number</h3><br>
<input type="text" name="toolbox_no" placeholder="e.g. 1"><br><br>
<h3>Drawer Number</h3><br>
<input type="text" name="drawer_no" placeholder="e.g. 1"><br><br>
<h3>Bin Number</h3><br>
<input type="text" name="bin_no" placeholder="e.g. 1"><br><br>
<h3>Product</h3><br>
<input type="text" name="product" placeholder="e.g. Widget #2"><br><br>
<input type="submit" value="Add to Tool Crib" name="submitbutton" action="submit"/>
</td>
</tr>
</table>
</form>
</div>
<?php
//If comments are open or we have at least one comment, load up the comment template
if ( comments_open() || '0' != get_comments_number() )
comments_template();
?>
<?php endwhile; // end of the loop. ?>
</div>
<div class="clear"></div>
</div>
</div>
</div>
<?php get_footer(); ?>
And here's the code for the php script to add form data to the database:
//MySQL Database
$servername = "url.com";
$username = "user_login";
$password = "user_password";
$datab = "database_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $datab);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = $_REQUEST['name'];
$type = $_REQUEST['type'];
$brand = $_REQUEST['brand'];
$part_number = $_REQUEST['part_number'];
$price = $_REQUEST['price'];
$oal = $_REQUEST['oal'];
$material = $_REQUEST['material'];
$cutting_diam = $_REQUEST['cutting_diam'];
$shank_diam = $_REQUEST['shank_diam'];
$flutes = $_REQUEST['flutes'];
$loc = $_REQUEST['loc'];
$corner_rad = $_REQUEST['corner_rad'];
$qty = $_REQUEST['qty'];
$trigger_qty = $_REQUEST['trigger_qty'];
$reorder_link = $_REQUEST['reorder_link'];
$toolbox_no = $_REQUEST['toolbox_no'];
$drawer_no = $_REQUEST['drawer_no'];
$bin_no = $_REQUEST['bin_no'];
$product = $_REQUEST['product'];
$username = $user_login;
$sql = "INSERT INTO `cutting tools` (`name`, `type`, `brand`, `part_number`, `reorder_link`, `oal`, `price`, `material`, `cutting_diam`, `shank_diam`, `flutes`, `loc`, `corner_rad`, `qty`, `trigger_qty`, `user`, `drawer_no`, `bin_no`, `toolbox_no`)
VALUES ('$name', '$type', '$brand', '$part_number', '$reorder_link', '$oal', '$price', '$material', '$cutting_diam', '$shank_diam', '$flutes', '$loc', '$corner_rad', '$qty', '$trigger_qty', '$username', '$drawer_no', '$bin_no', '$toolbox_no')";
if(mysqli_query($conn, $sql)){
echo "Record added successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($conn);
}
// Close connection
mysqli_close($conn);
?>
Also I know my database is vulnerable to injection, that was a change I planned on making once the form was up and running.
Use WordPress to your advantage. Instead of defining your own connection, use global $wpdb, and then use the insert command.
global $wpdb;
$success = $wpdb->insert('tbl_name', array(<br>
'field1_name' => $_REQUEST['field1'],<br>
'field2_name' => $_REQUEST['field2'],<br>
));<br>
if($success){<br>
echo "Inserted correctly";<br>
} else {<br>
echo "Something went awry!";<br>
}
Here's a prepared statement, a more secure way of creating a MYSQL record in your table.
<?php
//MySQL Database
$servername = "url.com";
$username = "user_login";
$password = "user_password";
$datab = "database_name";
// Create connection
$con = new mysqli($servername, $username, $password, $datab);
global $con;
// Post form data
$name = $_POST['name'];
$type = $_POST['type'];
$brand = $_POST['brand'];
$part_number = $_POST['part_number'];
$price = $_POST['price'];
$oal = $_POST['oal'];
$material = $_POST['material'];
$cutting_diam = $_POST['cutting_diam'];
$shank_diam = $_POST['shank_diam'];
$flutes = $_POST['flutes'];
$loc = $_POST['loc'];
$corner_rad = $_POST['corner_rad'];
$qty = $_POST['qty'];
$trigger_qty = $_POST['trigger_qty'];
$reorder_link = $_POST['reorder_link'];
$toolbox_no = $_POST['toolbox_no'];
$drawer_no = $_POST['drawer_no'];
$bin_no = $_POST['bin_no'];
$product = $_POST['product'];
// Prepared statement
$insert = mysqli_prepare($con, "insert into cutting tools (name,type,brand,part_number,reorder_link,oal,price,material,cutting_diam,shank_diam,flutes,loc,corner_rad,qty,trigger_qty,user,drawer_no,bin_no,toolbox_no) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
mysqli_stmt_bind_param($insert, "sssssssssssssssssss", $name,$type,$brand,$part_number,$reorder_link,$oal,$price,$material,$cutting_diam,$shank_diam,$flutes,$loc,$corner_rad,$qty,$trigger_qty,$product,$drawer_no,$bin_no,$toolbox_no);
mysqli_stmt_execute($insert);
if ($insert) { echo "success"; mysqli_close($con); } else { echo "error"; mysqli_close($con); }
?>
Pay close attention to the order of your columns and the data you are submitting to those columns. I have edited this post because your order was incorrect in several places.
The column names and the data variables being uploaded to them have to be in the exact same order if you want data created correctly.
By the way the variable $product does not seem to match the column name of user, you may want to check this.

Trouble getting FORM submitted to Mysql

I have one page which has one input text box and that data needs to be either inserted or updating the existing row.
I will echo it later, that is under control.
<form method="post" name="tapahtuma">
Submit:
<input type="text" name="auts[]">
<input type="button" value="Ilmoita">
</form >
<?php
if(isset( $_POST["tapahtuma"]) ) {
$link = mysql_connect("localhost","root","","db");
mysqli_query($link, "INSERT INTO table (column) VALUES ('".$auts."')");
$auts = mysql_real_escape_string($_POST['auts']);
mysqli_close($link);
}
?>
According to the code provided.
Changes
Change <input type="button" value="Ilmoita"> to <input type="submit" name="Ilmoita" value="Ilmoita">
Change if(isset( $_POST["tapahtuma"]) ) { to if(isset( $_POST["Ilmoita"]) ) {
Change $link = mysql_connect("localhost","root","","db"); to $link = mysqli_connect("localhost","root","","db");
Put $auts = mysql_real_escape_string($_POST['auts']); before mysqli_query
Updated Code
<form method="post" name="tapahtuma">
<input type="text" name="auts">
Submit: <input type="submit" name="Ilmoita" value="Ilmoita">
</form >
<?php
if(isset( $_POST["Ilmoita"]) ) {
$link = mysqli_connect("localhost","root","","db");
$auts = mysql_real_escape_string($_POST['auts']);
mysqli_query($link, "INSERT INTO table (column) VALUES ('".$auts."')");
mysqli_close($link);
}?>
I will suggest you to use prepared statements to avoid SQL Injections
<form method="post" name="tapahtuma">
<input type="text" name="auts">
Submit: <input type="submit" name="Ilmoita" value="Ilmoita">
</form>
<?php
if(isset($_POST["Ilmoita"])) {
$link = mysqli_connect("localhost","root","","db") or die("connection failed: " . mysqli_connect_error());
$result = mysqli_prepare($link, "INSERT INTO `table` (`column`) VALUES (?)");
mysqli_stmt_bind_param($result, "s", $_POST['auts']);
mysqli_stmt_execute($result);
mysqli_close($link);
}?>
Quick Links
mysqli_prepare
How can I prevent SQL injection in PHP?
<form method="post" name="tapahtuma">
Vapaa teksti: <input type="text" name="auts">
<input type="submit" value="ilmoita" name="ilmoita">
</form >
<?php
if(isset( $_POST["ilmoita"]) ) {
$link = mysqli_connect("localhost","root","","db");
$auts = mysqli_real_escape_string($link, $_POST['auts']);
mysqli_query($link, "INSERT INTO table (column) VALUES ('$auts')");
mysqli_close($link);
}?>
What I did, is that I used mysqli_real_escape_string instead of mysql_real_escape_string and also added the $link there as well.
I will test with the prepared statements sometime, but at least this works and it really isn't a concern with the sqli exploits.

Incorrect integer value: '' for column 'customerid' at row 1

I am working on my project for school and is now stuck on this problem that I hope someone here my point me in the right direction.
I am designing a booking system which uses a web front and MySQL database. I have a few tables: Customers, Seats, Price, Booking and Screening. I am trying to insert data into the booking table from the other tables using there primary keys. however I keep getting the following error message: Incorrect integer value: '' for column 'customerid' at row 1
I have search every where but doesn't seem to get any solution. I have copied my code below.
<?php
$customerid=$_POST['customerid'];
$screeningid=$_POST['screeningid'];
$seatid=$_POST['seatid'];
$priceid=$_POST['priceid'];
$status=$_POST['status'];
$query = "INSERT INTO `booking`(bookingid, customerid, screeningid, seatid, priceid, bookingdate, status)
VALUES(NULL, '". mysql_real_escape_string($customerid)."', '". mysql_real_escape_string($screeningid)."', '". mysql_real_escape_string($seatid)."','". mysql_real_escape_string($priceid)."', 'DateTime()', '". mysql_real_escape_string($status)."')";
$result=mysql_query($query) or die (mysql_error());
// if successfully insert data into database, displays message "Successful".
if($result)
{
echo "<p>success</p>";
echo "<BR>";
}
else
{
echo mysql_error();
}
?>
This is my Form:
<div id="content">
<h2>Enter Booking Details Below</h2>
<form name="reg_form" action="bookingecho.php?action=add type=booking" onsubmit="return validate_reg()" method="POST" >
<table>
<tr>
<td>Customer</td>
<td> <select name="customerid">
<?php
//Perform database query
$query = ("SELECT * FROM customers
ORDER BY customerid DESC");
$result = mysql_query($query, $connection) or die (mysql_error());
// populate the select options with the results
while ($row = mysql_fetch_assoc($result))
{
//extract column
$customerid = $row['customerid'];
$fname = $row['fname'];
$lname = $row['lname'];
$telephone = $row['telephone'];
//use
echo "<option value>$customerid $fname $lname $telephone</option>";
}
?>
</select></td></tr>
<tr>
<td>Screening</td>
<td> <select name="screeningid">
<?php
//Perform database query
$query = ("SELECT * FROM screening");
$result = mysql_query($query, $connection) or die (mysql_error());
// populate the select options with the results
while ($row = mysql_fetch_assoc($result))
{
//extract column
$screeningid = $row['screeningid'];
$day = $row['day'];
$screeningdate = $row['screeningdate'];
$filmtitle = $row['filmtitle'];
//use
echo "<option value>$screeningid $day $screeningdate $filmtitle</option>";
}
?>
</select></td></tr>
<tr>
<td>Seat</td>
<td> <select name="seatid">
<?php
//Perform database query
$query = ("SELECT seats.seatid, seats.seatnumber, seats.seatclass
FROM seats
WHERE seatid
NOT IN (SELECT seatid FROM booking
WHERE screeningid = '$screeningid')
ORDER BY `Seats`.`seatid` ASC");
$result = mysql_query($query, $connection) or die (mysql_error());
// populate the select options with the results
while ($row = mysql_fetch_assoc($result))
{
//extract column
$seatid = $row['seatid'];
$seatnumber = $row['seatnumber'];
$seatclass = $row['seatclass'];
//use
echo "<option value>$seatid $seatnumber $seatclass</option>";
}
?>
</select></td></tr>
<tr>
<td>Concession</td>
<td> <select name="priceid">
<?php
//Perform database query
$query = ("SELECT * FROM price");
$result = mysql_query($query, $connection) or die (mysql_error());
// populate the select options with the results
while ($row = mysql_fetch_assoc($result))
{
//extract column
$priceid = $row['priceid'];
$concession = $row['concession'];
$cost = $row['cost'];
//use
echo "<option value>$priceid $concession $cost</option>";
}
?>
</select></td></tr>
<tr>
<td>Status</td>
<td>
<input type= radio name="status" value="Booked"> Booked
<input type= radio name="status" value="Reserved"> Reserved
</td>
</tr>
</select></td></tr>
</table>
<p align="center">
<td><input type="submit" name="submit" id= "submit" value="Add"/></td>
<input type="reset" value="Reset Form">
</p>
</form>
</div>
Use intval() for integer values.
Use mysql_real_escape_string on strings, Never for integers.
Single quotes around integer values in a mySQL query is optional.
Because intval() guarantees $customerid is an integer value, the quotes are not necessary and will never generate an error.
I have only included the two lines of code directly related to your customer id. The same likely applies to the other values as well.
$customerid=intval($_POST['customerid']);
$query = "INSERT INTO `booking`
(`bookingid`, `customerid`, `screeningid`,`seatid`,`priceid`, `bookingdate`, `status`)
VALUES(NULL,$customerid,'$screeningid','$seatid','$priceid',CURDATE(),'$status')";
Change:
<input name="status" value="Booked" type="radio"> Booked
<input name="status" value="Reserved" type="radio"> Reserved
To:
<input name="status" value="1" type="radio"> Booked
<input name="status" value="2" type="radio"> Reserved
Always submit integer values greater then zero whenever possible. They are easy to validate. To get the text back:
$statuses = array('unknown','booked','reserved')
$strStatus = $statuses[$status];
UPDATE FOREIGN KEY CONSTRAINT ERROR
A CONSTRAINT ERROR says you do not have a customer record for the added booking table. Or the foreign key is wrong. The foreign key is not needed.
You could combine the customer add, lookup and booking INSERT at the same time.
Rather than some sort of login to create or retrieve the customer record get the booking then during the last step in the booking process just ask for the phone number. Personally I do not care if someone were to query the system with my phone number and found out which seat I have. Some might. But asking for a a login in before getting the booking is a nuisance and a road block to finalizing the booking.
What I did was add the security ID
If they want to secure their seats with a password let it be their choice.
If the record does not exist, then ask for their name AFTER the seats are booked.
//$customerid = intval($_POST['customerid']);
$screeningid = intval($_POST['screeningid']);
$seatid = intval($_POST['seatid']);
$priceid = intval($_POST['priceid']);
$status = intval($_POST['status']);
$fname = mysql_real_escape_string($_POST['status']);
$lname = mysql_real_escape_string($_POST['lname']);
$telephone = intval(preg_replace('/[^D]/','',$_POST['telephone']));
//must have UNIQUE Index on `telephone`
$sql = "INSERT INTO `customer` (`customerid`,`fname`, `lname`, `telephone`)
VALUES(NULL,'', '', $telephone)";
$result = mysql_query($sql);
if(mysql_insert_id()){
$customerid = mysql_insert_id();
}
else{
list($customerid, $fname`, $lname,$id) = mysql_fetch_array(mysql_query(
"SELECT `customerid`,`fname`, `lname`, `telephone`,`id`
FROM `customer` WHERE `telephone`=$telephone"),MYSQL_NUM);
}
$query = "INSERT INTO `booking`
(`bookingid`, `customerid`, `screeningid`,`seatid`,`priceid`, `bookingdate`, `status`)
VALUES(NULL,$customerid,$screeningid,$seatid,$priceid,CURDATE(),$status)";
echo <<<EOT
<p>Your seats are booked.</p>
<form action="update.php" method="post">
<label>Last:</label>
<input type="text" name="lname" value="$lname" />
<br/>
<label>First:</label>
<input type="text" name="fname" value="$fname" />
<br/>
<label>Phone:</label>
<input type="tel" name="telephone" value="$telephone" />
<br/>
<p class="footnote">Security ID is optional</p>
<label>Security ID:</label>
<input type="text" name="id" value="$id" />
<br/>
<input type="hidden" name="phone" value="$telephone" />
<br/>
<div class="footnote">
If you want to keep your booking secure then enter a security id.
<br>If blank, no security ID will be necessary to retrieve your seats in the future.
<br/>This can be any number (e.g. PIN) word, or any characters.
<br/>Maximum 16 characters.</p>
<p>Do NOT use an existing high security password (e.g. your banking password)</p>
<h4>If you would like your seats sent to you via text,<br/>Select your mobile carrier<br/>This will also verify you entered the correct phone number</h4>
</div>
<label>Mobile Carrier</label>
<select>
<option value="">No Text / Land Line</option>
<option value="#message.alltel.com">Alltel</option>
<option value="#paging.acswireless.com">Ameritech</option>
<option value="#mmode.com">ATT Wireless</option>
<option value="#bellsouth.cl">Bellsouth</option>
<option value="#myboostmobile.com">Boost</option>
<option value="#mobile.celloneusa.com">CellularOne</option>
<option value="#mobile.mycingular.com">Cingular</option>
<option value="#sms.edgewireless.com">Edge Wireless</option>
<option value="#mymetropcs.com">Metro PCS</option>
<option value="#messaging.nextel.com">Nextel</option>
<option value="#mobile.celloneusa.com">O2</option>
<option value="#mobile.celloneusa.com">Orange</option>
<option value="#qwestmp.com">Qwest</option>
<option value="#pcs.rogers.com">Rogers Wireless</option>
<option value="#messaging.sprintpcs.com">Sprint PCS</option>
<option value="#teleflip.com">Teleflip</option>
</optgroup>
<option value="#msg.telus.com">Telus Mobility</option>
<option value="#email.uscc.net">US Cellular</option>
<option value="#vtext.com">Verizon</option>
</select>
<br/>
<input type="submit" value="Save Changes" />
</form>
EOT;
FORM SNIPPET
label {
width: 5em;
display: inline-block;
text-align: right;
}
.footnote {
margin: .5em 0 .5em 5em;
}
input[type="submit"] {
margin: 1em 6em;
}
h4 {
margin-bottom: 0;
}
<p>Your seats are booked.</p>
<form action="update.php" method="post">
<label>Last:</label>
<input type="text" name="lname" value="$lname" />
<br/>
<label>First:</label>
<input type="text" name="fname" value="$fname" />
<br/>
<label>Phone:</label>
<input type="tel" name="telephone" value="$telephone" />
<br/>
<p class="footnote">Security ID is optional</p>
<label>Security ID:</label>
<input type="text" name="id" value="$id" />
<br/>
<input type="hidden" name="phone" value="$telephone" />
<br/>
<div class="footnote">
If you want to keep your booking secure then enter a security id.
<br>If blank, no security ID will be necessary to retrieve your seats in the future.
<br/>This can be any number (e.g. PIN) word, or any characters.
<br/>Maximum 16 characters.</p>
<p>Do NOT use an existing high security password (e.g. your banking password)</p>
<h4>If you would like your seats sent to you via text,<br/>Select your mobile carrier<br/>This will also verify you entered the correct phone number</h4>
</div>
<label>Mobile Carrier</label>
<select>
<option value="">No Text / Land Line</option>
<option value="#message.alltel.com">Alltel</option>
<option value="#paging.acswireless.com">Ameritech</option>
<option value="#mmode.com">ATT Wireless</option>
<option value="#bellsouth.cl">Bellsouth</option>
<option value="#myboostmobile.com">Boost</option>
<option value="#mobile.celloneusa.com">CellularOne</option>
<option value="#mobile.mycingular.com">Cingular</option>
<option value="#sms.edgewireless.com">Edge Wireless</option>
<option value="#mymetropcs.com">Metro PCS</option>
<option value="#messaging.nextel.com">Nextel</option>
<option value="#mobile.celloneusa.com">O2</option>
<option value="#mobile.celloneusa.com">Orange</option>
<option value="#qwestmp.com">Qwest</option>
<option value="#pcs.rogers.com">Rogers Wireless</option>
<option value="#messaging.sprintpcs.com">Sprint PCS</option>
<option value="#teleflip.com">Teleflip</option>
</optgroup>
<option value="#msg.telus.com">Telus Mobility</option>
<option value="#email.uscc.net">US Cellular</option>
<option value="#vtext.com">Verizon</option>
</select>
<br/>
<input type="submit" value="Save Changes" />
</form>
The error message means you are getting an "empty string" ('') for customerid, which simply means that your first chunk of code is not getting any value at all for that field when the form is submitted.
Here is the problem:
echo "<option value>$customerid $fname $lname $telephone</option>";
The values between <option> and </option> are what will be displayed to the end-user, but they will not be submitted with your form, which means they won't be available to that first chunk of code.
To submit the customerid, you have to put it into the value part:
echo "<option value=$customerid>$customerid $fname $lname $telephone</option>";
You placed apostrophes around $customerid (and other non-string values) when it is actually an integer inside your database. Delete the apostropes (') around all values that are meant to be integers in your database (I have a feeling that is the case for many of your variables). Also please organize your code because it was extremely difficult to look at it without crying :)
<?php
$customerid=mysql_real_escape_string($_POST['customerid']);
$screeningid=$_POST['screeningid'];
$seatid=mysql_real_escape_string($_POST['seatid']);
$priceid=mysql_real_escape_string($_POST['priceid']);
$status=mysql_real_escape_string($_POST['status']);
$query = "INSERT INTO `booking`(bookingid, customerid,
screeningid, seatid, priceid, bookingdate, status)
VALUES (NULL, ". $customerid.", ". $screeningid.", ".
$seatid.", ".$priceid.", 'DateTime()', '".$status."')";
$result=mysql_query($query) or die (mysql_error());
// if successfully insert data into database, displays message "Successful".
if($result)
{
echo "<p>success</p><br>";
}
else
{
echo mysql_error();
}
?>
Also note, DateTime() is a php function, not an SQL command. I left it in the previous code but be aware that you should fix that error.
Let me know if this worked for you.

Inserting multiple row in database using php form

I created a form which can add more input field for product_name and quantity of the product with the help of jquery, this is the demo where you can add more input field in the form.
the problem is when i submit the form only the last product will submit into my database the rest of the product will not submitted.
this is my query
<?php
if(isset($_POST['submit'])){
//process the form
$date = $_POST["date"];
$customer_name = $_POST["customer_name"];
$product_description = $_POST["product_description"];
$quantity = $_POST["quantity"];
$status = $_POST["status"];
$query = "
INSERT INTO orders (
date, customer_name, product_description, quantity, status
) VALUES (
'$date', '$customer_name', '$product_description',$quantity,$status
)";
$order_set = mysqli_query($connection, $query);
if($order_set){
redirect_to("index.php");
}
} else {
// failed
}
?>
My Form
<form action="order.php" method="post">
<div class="newOrder">
<p><span>Date</span><input type="date" value="2014-12-01" name="date" /></p>
<p><span>Name</span>
<select name="customer_name">
<?php
while($customer = mysqli_fetch_assoc($customers_set)){ ?>
<option><?php echo $customer['customer_name']; ?></option>
<?php } ?>
<?php mysqli_free_result($customers_set); ?>
</select>
</p>
<div id="input_fields">
<p><span>Product Description</span>
<select name="product_description">
<?php
while($product = mysqli_fetch_assoc($product_set)){ ?>
<option><?php echo $product['product_description']; ?></option>
<?php } ?>
<?php mysqli_free_result($product_set); ?>
</select>
<input value="0" type="text" name="quantity" />
</p>
</div>
Add More Product
<p class="radio">
<input type="radio" name="status" value="0" checked />For delivery
<input type="radio" name="status" value="1" />For payment confirmation
<input type="radio" name="status" value="2" />Reserved items
</p>
<input type="submit" name="submit" value="Create Order" />
</div>
</form>
any body have any idea how to submit all product and quantity input in input field will be save in database.
Wrap your values inside your database connection. Consider this from one of my old course. Notice is a different code however working perfectly.
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$when_it_happened = $_POST['whenithappened'];
$how_long = $_POST['howlong'];
$how_many = $_POST['howmany'];
$alien_description = $_POST['aliendescription'];
$what_they_did = $_POST['whattheydid'];
$fang_spotted = $_POST['fangspotted'];
$email = $_POST['email'];
$other = $_POST['other'];
$dbc = mysqli_connect('data.aliensabductedme.com', 'owen', 'aliensrool', 'aliendatabase')
or die('Error connecting to MySQL server.');
$query = "INSERT INTO aliens_abduction (first_name, last_name, when_it_happened, how_long, " .
"how_many, alien_description, what_they_did, fang_spotted, other, email) " .
"VALUES ('$first_name', '$last_name', '$when_it_happened', '$how_long', '$how_many', " .
"'$alien_description', '$what_they_did', '$fang_spotted', '$other', '$email')";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
mysqli_close($dbc);
The input fields have the same name? So I guess thats why only the last one get inserted.
You have to loop the INSERT query foreach product you add, this includes quantity.
You should allso sanitize the input value before you inserting it to a query.
When you inserting multiple queries, you shouldn't do that from the php loop. Is not efficient because you are executing multiple queries instead one or two. You can loop trough the results sent from the form, clean it and prepare it for database insertion, and after that build a query based on that results. Look at here for the inserting multiple rows at once into a database :
(Insert multiple rows with one query MySQL)
you need to use foreach
foreach ($_POST['quantity'] as $quantity) {
//insert code
}

Data insertion issues with HTML form and PHP to mySQL

I have seen few posts in SO related to the same scenario as mine but did not find a proper resolution. So am posting question with my problem stuff.
I have an HTML form
<form method="post" id="myForm">
<label for="e_name">Name</label>
<input name="e_name" id="emp_name" value="" type="text" data-theme="a">
<label for="date">Date</label>
<input name="date" id="emp_dob" value="" data-theme="a">
<label for="gender">Gender</label>
<select name="gender" id="emp_gender" data-role="slider" data-theme="a" data-inline="true">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<label for="address">Address</label>
<textarea name="address" id="emp_address" value="" type="text" data-theme="a"></textarea><br><br>
<input type="button" id="insert" value="Submit">
</form>
<div id="someElement"></div>
And I have the following to perform my form elements submission to a PHP page-
$(document).ready(function(){
$("#insert").click(function(e) {
e.preventDefault();
alert("am in the Insert function now");
$.ajax({
cache: false,
type: 'POST',
url: 'insert.php',
data: $("#myForm").serialize(),
success: function(d) {
$("#someElement").html(d);
}
});
});
});
Here is my PHP -
<?php
$con=mysqli_connect("localhost","root","root","employee");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name =" ";
$dob =" ";
$gender =" ";
$address =" ";
if(isset($_POST['emp_name'])){ $name = $_POST['emp_name']; }
if(isset($_POST['emp_dob'])){ $dob = $_POST['emp_dob']; }
if(isset($_POST['emp_gender'])){ $gender = $_POST['emp_gender']; }
if(isset($_POST['emp_address'])){ $address = $_POST['emp_address']; }
echo $name;
echo $dob;
echo $gender;
echo $address;
$sql="INSERT INTO emp_details (emp_name, emp_gender, emp_address) VALUES ('$name', '$gender', '$address')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Now what happens is, when I enter some values in my form and click on Submit, action performs well and a new row inserts in the database. But all the rows are empty. They're just empty, not even "NULL".
I tried to echo my field values in the PHP but there is no output there. My "1 Record Added" has come-up well, but no form values appear here.
Kindly help me sorting this out.
Thanks in advance.
$_POST[] references to the name attribute of html-tag, not id.
For example, $_POST['emp_name'] should be $_POST['e_name']
Furthermore, don't encapsulate your variables with single quotes:
"INSERT INTO emp_details (emp_name, emp_gender, emp_address) VALUES ('$name', '$gender', '$address')";
Do this instead:
"INSERT INTO emp_details (emp_name, emp_gender, emp_address) VALUES ('" . $name . "', '" . $gender . "', '" . $address . "')";
Or use bind_param() from mysqli ofcourse!
Make the id and name of your input elements same
<form method="post" id="myForm">
<label for="e_name">Name</label>
<input name="emp_name" id="emp_name" value="" type="text" data-theme="a">
<label for="date">Date</label>
<input name="emp_dob" id="emp_dob" value="" data-theme="a">
<label for="gender">Gender</label>
<select name="emp_gender" id="emp_gender" data-role="slider" data-theme="a" data-inline="true">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<label for="address">Address</label>
<textarea name="emp_address" id="emp_address" value="" type="text" data-theme="a"></textarea><br><br>
<input type="button" id="insert" value="Submit">
</form>
Otherwise change your $_POST array keys.Because you will get the keys of $_POST array will be the name of input elements.But i recommend you to mak ethe name and id same

Categories