as you see in this code i made a table by selecting models from table in my database..
however i posted the return of the select query to be like the primary column for this table and put it into the while loop so it keeps generating rows till the models which came with the select query be finished
now i got a a problem when i'm trying to get this models in a $_Post[''] supergloble it keeps send me only the last value it gets from the loop
my question is how to get each and every value from the this loop to use it in a single insert query in my DB?
and sorry for the bad English :S !!
<form class="form-signin" action="<?php $_SERVER['PHP_SELF'];?>" method="Post">
<?php
$models = mysql_query("SELECT `Model_Name` FROM `models` WHERE `Brand` = 20");
while($row = mysql_fetch_array($models))
{
echo '
<tr>
<td><input type="text" name="mode[]" value="'.$row['Model_Name'].'"></td>
<td><input type="text" name="sellout[]" value=""></td>
<td><input type="text" name="shelfshare[]" value=""></td>
<td><input type="text" name="price[]" value=""></td>
<td><input type="text" name="Shortage[]" value=""></td>
<td><input type="text" name="Inventory[]" value=""></td>
</tr>
';
}
?>
</form>
the inserting script
$date = date("Y-m-d");
foreach($_POST['mode'] as $key => $mode){
$sellout = $_POST['sellout'][$key];
$shelfshare = $_POST['shelfshare'][$key];
$price = $_POST['price'][$key];
$shortage = $_POST['shortage'][$key];
$inventory = $_POST['inventory'][$key];
mysql_query("INSERT INTO `smartdailyreport`(`SFO_Code`, `Model`, `Sell_Out`, `Shelf_Share`, `Price`, `Shortage`, `Inventory`, `Date`) VALUES ('".mysql_real_escape_string($_SESSION['idd'])."','".mysql_real_escape_string($mode)."','".mysql_real_escape_string($sellout)."','".mysql_real_escape_string($shelfshare)."','".mysql_real_escape_string($price)."','".mysql_real_escape_string($shortage)."','".mysql_real_escape_string($inventory)."','".mysql_real_escape_string($date)."')") or die(mysql_error());
}
Make the name of those inputs an array :
<tr>
<td><div class="col3" align="center"><input type="text" name="mode[]" class="form-control" value="'.$row['Model_Name'].'"></div></td>
<td><div class="col3" align="center"><input type="text" name="sellout[]" class="form-control" value=""></div></td>
<td><div class="col3" align="center"><input type="text" name="shelfshare[]" class="form-control" value=""></div></td>
<td><div class="col3" align="center"><input type="text" name="price[]" class="form-control" value=""></div></td>
<td><div class="col3" align="center"><input type="text" name="Shortage[]" class="form-control" value=""></div></td>
<td><div class="col3" align="center"><input type="text" name="Inventory[]" class="form-control" value=""></div></td>
</tr>
Then when you process the form:
foreach($_POST['mode'] as $key=>$mode){
$thisIsOne = $_POST['mode'][$key];
$alsoThisOne = $_POST['sellout'][$key];
etc...
}
I'll put my comments into an answer for you...
You've got $POST as your $mode value, fix that up. (or remove it, $mode is already defined from the foreach)
Put your query inside your foreach loop, otherwise you just overwrite those variables each time you iterate, then insert the last one at the end
Put mysql_error into the die callback of mysql_query to show you an error if there is one (if you want to)
$date = date("Y-m-d");
foreach($_POST['mode'] as $key => $mode){
$sellout = $_POST['sellout'][$key];
$shelfshare = $_POST['shelfshare'][$key];
$price = $_POST['price'][$key];
$shortage = $_POST['shortage'][$key];
$inventory = $_POST['inventory'][$key];
mysql_query("INSERT INTO `smartdailyreport`(`SFO_Code`, `Model`, `Sell_Out`, `Shelf_Share`, `Price`, `Shortage`, `Inventory`, `Date`) VALUES ('".mysql_real_escape_string($_SESSION['idd'])."','".mysql_real_escape_string($mode)."','".mysql_real_escape_string($sellout)."','".mysql_real_escape_string($shelfshare)."','".mysql_real_escape_string($price)."','".mysql_real_escape_string($shortage)."','".mysql_real_escape_string($inventory)."','".mysql_real_escape_string($date)."')") or die(mysql_error());
}
Lastly, use mysqli_* instead of mysql as mysql has been deprecated for some time now. And also, use mysqli_real_escape_string or similar to escape your POST variables and save you from SQL Injection
Related
I set up an HTML with a form that would send the information over to a PHP page. Then the PHP would run through it and send it to my DB. I set it the database up in cPanel. I have another part to the code that searches for the item and that works. I just don't get why the query statement in this isn't pulling the information.
The error that I get is "An error has occurred. The item was not added." which I have set up after the query line. I can't seem to figure out why.
Here is the code:
html:
<form action="insert_product.php" method="post">
<table border="0">
<tr>
<td>ShoeName</td>
<td><input type="text" name="ShoeName" maxlength="13" size="13"></td>
</tr>
<tr>
<td>Price</td>
<td> <input type="text" name="Price" maxlength="7" size="7"></td>
</tr>
<tr>
<td>ProductID</td>
<td> <input type="text" name="ProductID" maxlength="7" size="7"></td>
</tr>
<tr>
<td>Size</td>
<td><input type="text" name="Size" maxlength="7" size="7"></td>
</tr>
<tr>
<td>ShoeType</td>
<td><input type="text" name="ShoeType" maxlength="7" size="7"></td>
</tr>
<tr>
<td>Brand</td>
<td><input type="text" name="Brand" maxlength="7" size="7"></td>
</tr>
<tr>
<td>Color</td>
<td><input type="text" name="Color" maxlength="7" size="7"></td>
</tr>
<tr>
<td>Rating</td>
<td><input type="text" name="Rating" maxlength="7" size="7"></td>
</tr>
<tr>
<td>Description</td>
<td><input type="text" name="Description" maxlength="40" size="40"></td>
</tr>
<tr>
<td>ImageName</td>
<td><input type="text" name="ImageName" maxlength="7" size="7"></td>
</tr>
<tr>
<td>StockAmount</td>
<td><input type="text" name="StockAmount" maxlength="7" size="7"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Register"></td>
</tr>
</table>
php:
<?php
// create short variable names
$ShoeName=$_POST['ShoeName'];
$Price=$_POST['Price'];
$ProductID=$_POST['ProductID'];
$Size=$_POST['Size'];
$ShoeType=$_POST['ShoeType'];
$Brand=$_POST['Brand'];
$Color=$_POST['Color'];
$Rating=$_POST['Rating'];
$Description=$_POST['Description'];
$ImageName=$_POST['ImageName'];
$StockAmount=$_POST['StockAmount'];
if (!$ShoeName || !$Price || !$ProductID || !$Size || !$ShoeType || !$Brand || !$Color || !$Rating || !$Description || !$ImageName || !$StockAmount) {
echo "You have not entered all the required details.<br />"
."Please go back and try again.";
exit;
}
if (!get_magic_quotes_gpc()) {
$ShoeName = addslashes($ShoeName);
$Price = doubleval($Price);
$ProductID = addslashes($ProductID);
$Size = addslashes($Size);
$ShoeType = addslashes($ShoeType);
$Brand = addslashes($Brand);
$Color = addslashes($Color);
$Rating = doubleval($Rating);
$Description = addslashes($Description);
$ImageName = addslashes($ImageName);
$StockAmount = doubleval($StockAmount);
}
# $db = new mysqli('localhost', 'admin', '(pass)', 'KicksUnlimited');
if (mysqli_connect_errno()) {
echo "Error: Could not connect to database. Please try again later.";
exit;
}
$query = "INSERT INTO product".'(ShoeName, Price, ProductID, Size, ShoeType, Brand, Color, Rating, Description, ImageName, StockAmount)'."values
('".$ShoeName."', '".$Price."', '".$ProductID."', '".$Size."', '".$ShoeType."', '".$Brand."', '".$Color."', '".$Rating."', '".$Description."', '".$ImageName."', '".$StockAmount."')";
$result = $db->query($query);
if ($result) {
echo $db->affected_rows." shoe inserted into database.";
} else {
echo "An error has occurred. The item was not added.";
}
$db->close();
?>
Test:
type query in cpanel with values not variable.
Use print $ShoeName=$_POST['ShoeName']; in front of every $_POST[] and on the end print exit; It is to control that value coming from Form.
Comment all between variables $_POST[] and INSERT INTO .....
Control quote. It is mess of quote, double, single, it does not need. And control if it is need quote around every values.
Sorry, I have not time to do all that for to find for sure error.
Do it yourself because it is the best way of learning.
I am HR and new for Developing. I started doing program for HR management using PHP and Mysql. I want to add the names of atleast 5 employees in a single row of a column. I use bootstrap to get multiple values in a single field. But when I try to insert the values, only the last value is inserted.
<td>Distribute</td><td><input type="text" class="form-control" name="distribute[]"></td>
HTML Code:
<tr><td>Distribute</td><td><input type="text" class="form-control" name="distribute[]"></td></tr>
PHP to insert into mysql
$civil_id= $_POST['civil_id'];
$name= $_POST['name'];
$card_type = $_POST['card_type'];
$count = $_POST['count'];
$amt=$card_type * $count;
$avail_bal=$_POST['balance']- $amt;
$issue_year= $_POST['issue_year'];
$issue_month= $_POST['issue_month'];
$issue_date= $_POST['issue_date'];
$distribute= $_POST['distribute'];
$sql ="insert into group_phone
(civil_id,
name,
card_type,
count,
amt,
avail_bal,issue_year,issue_month,issue_date,distribute)values('$civil_id',
'$name',
'$card_type',
'$count',
'$amt',
'$avail_bal','$issue_year','$issue_month','$issue_date','$distribute')";
HTML
<script>
$(document).ready(function() {
$(".select2_single").select2({
placeholder: "Select Vehicle Plate Number",
allowClear: true
});
$(".select2_group").select2({});
$(".select2_multiple").select2({
maximumSelectionLength: 10,
placeholder: "With Max Selection limit 10",
allowClear: true
});
});
</script>
<form class="form-horizontal form-label-left" action="new_rechargecard.php" method="POST" ">
<table id="datatable" class="table table-striped table-bordered">
<tbody>
<tr>
<td width='100'>Employee Name: </td><td><input type="text" class="form-control" placeholder="0" name="name" value="<?php echo "$name";?>" ></td>
</tr>
<tr>
<td>Available Balance</td><td><input type="text" class="form-control" placeholder="0" name="balance" value=<?php echo $balance;?> > </td></tr>
<tr><td>Civil id</td><td><input type="text" class="form-control" placeholder="Civil ID Required" name="civil_id" value=<?php echo $pass_name;?> > </td></tr>
<!--<tr><td>Name</td><td><input type="text" class="form-control" name="name" value="<?php echo $name;?>" > </td></tr>-->
<tr><td width='250'>Card Type (1 KD or 2.5 KD or 5 KD)</td><td><input type="text" class="form-control" name="card_type"></td></tr>
<tr><td width='200'>Card Count</td><td><input type="text" class="form-control" name="count"></td></tr>
<tr><td>Issue Year</td><td><input type="text" class="form-control" name="issue_year" value="<?php echo date('Y'); ?>"></td></tr>
<tr><td>For the Month of</td><td><input type="text" class="form-control" name="issue_month" value="<?php echo date('M'); ?>"></td></tr>
<tr><td>Issue date</td><td><input type="text" class="form-control" name="issue_date"></td></tr>
<tr><td>Distribute</td><td><select name="distribute" class="select2_multiple form-control" tabindex="-1" multiple="multiple">
<option></option>
<option>Richard Marcus</option>
<option>Rowlant S Peter</option>
<option>David.K.Rumpell</option>
<option>John Mathew</option>
</select>
</td></tr>
<tr><td></td><td><input type="submit" class="btn btn-round btn-danger" value="Update" name="submit"></td></tr>
</tbody>
</table>
</form>
Change your code like this
<?php
/* First create mysql connection */
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "userlist";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
/* End */
$civil_id= $_POST['civil_id'];
$name= $_POST['name'];
$card_type = $_POST['card_type'];
$count = $_POST['count'];
$amt=$card_type * $count;
$avail_bal=$_POST['balance']- $amt;
$issue_year= $_POST['issue_year'];
$issue_month= $_POST['issue_month'];
$issue_date= $_POST['issue_date'];
$distribute= $_POST['distribute'];
$sql ="insert into group_phone
(civil_id,
name,
card_type,
count,
amt,
avail_bal,issue_year,issue_month,issue_date,distribute)values('".$civil_id."',
'".$name."',
'".$card_type."',
'".$count."',
'".$amt."',
'".$avail_bal."','".$issue_year."','".$issue_month."','".$issue_date."','".$distribute."')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
MySQL table structure
-- Table structure for table userlist
CREATE TABLE IF NOT EXISTS `userlist` (
`civil_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`card_type` varchar(100) NOT NULL,
`count` int(11) NOT NULL,
`amt` int(11) NOT NULL,
`avail_bal` int(11) NOT NULL,
`issue_year` int(11) NOT NULL,
`issue_month` varchar(50) NOT NULL,
`issue_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`distribute` varchar(200) NOT NULL,
PRIMARY KEY (`civil_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
Working Query (MySQL)
INSERT INTO `userlist` (`civil_id`, `name`, `card_type`, `count`, `amt`, `avail_bal`, `issue_year`, `issue_month`, `issue_date`, `distribute`) VALUES
(1, 'aman,suresh,mohan', 'POST', 10, 500, 50, 2016, 'March', '2017-02-01 06:46:16', 'Airtel,Idea,Vodafone');
Not sure if you have solved this, but you just need to do an arrayed distribute name in the form then use a built-in function to turn the array to string, some popular functions are serialize() or json_encode(). I prefer the latter because JavaScript can use it, but in terms of best practice, it is generally frowned upon to store an array into a database like this. I have found it is useful for one-time instances where targeted searching is not required now or in the future. I would use it very sparingly. In this instance you may want to create a separate table that stores the names separately and join them when you go to select them later.
Also, for my example, I have used PDO instead of mysqli_ but the principles are the same. Look into bind_param. Finally, I would look at creating some useful classes that will help clean up the script. The ones I have below are some basic examples.
/classes/User.php
# I would think about containing your script in a class, this is just
# a bare-bones example
class User
{
public function __construct(PDO $db)
{
$this->db = $db;
}
protected function getAmount($a, $b)
{
return $a*$b;
}
protected function getBalance($a,$b)
{
return $a-$b;
}
public function addUser($array)
{
$bind = array(
$_POST['civil_id'],
$_POST['name'],
$_POST['card_type'],
$_POST['count'],
$amt = $this->getAmount($_POST['card_type'],$_POST['count']),
$this->getBalance($_POST['balance'],$amt),
$_POST['issue_year'],
$_POST['issue_month'],
$_POST['issue_date'],
json_encode($_POST['distribute'])
);
$sql ="INSERT INTO group_phone
(civil_id,name,card_type,count,amt,avail_bal,issue_year,issue_month,issue_date,distribute)
values
(?,?,?,?,?,?,?,?,?,?)";
$query = $this->db->prepare($sql);
$query->execute($bind);
}
}
/classes/Database.php
# This would need to be filled out and made to work with yours
# This is demonstration purposes only
class Database
{
private static $con;
public function connect()
{
if(self::$con instanceof PDO)
return self::$con;
self::$con = new PDO("mysql:host=localhost;dbname=databasename;","username","password");
return self::$con;
}
}
/new_rechargecard.php
define('DS', DIRECTORY_SEPARATOR);
define('ROOT_DIR', __DIR__);
define('CLASSES', ROOT_DIR.DS.'classes');
# Create a class autoloader
spl_autoload_register(function($class){
$inc = CLASSES.DS.trim(str_replace('\\',DS,$class),DS).'.php';
if(file_exists($inc))
include_once($inc);
});
# Create db
$con = (new Database())->connect();
# Check for update
if(isset($_POST['action']) && $_POST['action'] == 'update_user') {
# Create user instance
$User = new User($con);
# Add into database
$User->addUser($_POST);
}
?>
Form HTML:
<form class="form-horizontal form-label-left" action="new_rechargecard.php" method="POST">
<input type="hidden" name="action" value="update_user" />
<table id="datatable" class="table table-striped table-bordered">
<tbody>
<tr>
<td width='100'>Employee Name: </td>
<td><input type="text" class="form-control" placeholder="0" name="name" value="<?php echo $name ?>" ></td>
</tr>
<tr>
<td>Available Balance</td>
<td><input type="text" class="form-control" placeholder="0" name="balance" value=<?php echo $balance ?> ></td>
</tr>
<tr>
<td>Civil id</td>
<td><input type="text" class="form-control" placeholder="Civil ID Required" name="civil_id" value=<?php echo $pass_name;?> ></td>
</tr>
<tr>
<td width='250'>Card Type (1 KD or 2.5 KD or 5 KD)</td>
<td><input type="text" class="form-control" name="card_type"></td>
</tr>
<tr>
<td width='200'>Card Count</td>
<td><input type="text" class="form-control" name="count"></td>
</tr>
<tr>
<td>Issue Year</td>
<td><input type="text" class="form-control" name="issue_year" value="<?php echo date('Y'); ?>"></td>
</tr>
<tr>
<td>For the Month of</td>
<td><input type="text" class="form-control" name="issue_month" value="<?php echo date('M'); ?>"></td>
</tr>
<tr>
<td>Issue date</td>
<td><input type="text" class="form-control" name="issue_date"></td>
</tr>
<tr>
<td>Distribute</td>
<td><select name="distribute[]" class="select2_multiple form-control" tabindex="-1" multiple="multiple">
<option></option>
<option>Richard Marcus</option>
<option>Rowlant S Peter</option>
<option>David.K.Rumpell</option>
<option>John Mathew</option>
</select></td>
</tr>
<tr>
<td></td>
<td><input type="submit" class="btn btn-round btn-danger" value="Update"></td>
</tr>
</tbody>
</table>
</form>
I am trying to run a php upload which checks to see if a serial number already exists then if it doesnt submits data.
so :
Submit form --> PHP Checks DB for Duplicate Serial number --> If Serial number Does not Exist then post data // If Does Exist ignore input
However what ever i try doesnt seem to work. The following is my code but no matter what i do it submits the data even though the serial number already exists.
Form:
<form id="form1" action="senddata.php" name="form1" method="post">
<table class="table2" cellpadding="0" cellspacing="0">
<tr><td colspan="3"><input type="button" onClick="update()" value="Get Details"></td></tr>
<tr>
<td><label for="description">Description:</label></td>
<td><input tabindex="0" required type="text" name="description" id="description"></td>
</tr>
<tr>
<td><label for="nameofcomputer">Computer Code:</label></td>
<td><input tabindex="1" required type="text" name="nameofcomputer" id="nameofcomputer"></td>
</tr>
<tr>
<td><label for="make">Make:</label></td>
<td><input tabindex="2" required type="text" name="make" id="make"></td>
</tr>
<tr>
<td><label for="model">Model:</label></td>
<td><input tabindex="3" required type="text" name="model" id="model"></td>
</tr>
<tr>
<td><label for="serial">Serial Number:</label></td>
<td><input tabindex="4" required type="text" name="serial" id="serial"></td>
</tr>
<tr>
<td><label for="inputname">Your Name: </label></td>
<td><input tabindex="5" required id="inputname" name="inputname">
</td>
</tr>
</table>
<input required type="submit" name="submit" id="submit" value="Submit">
</form>
PHP
$desc=$_POST['description'];
$code=strtoupper($_POST['nameofcomputer']);
$make=$_POST['make'];
$model=$_POST['model'];
$serial=strtoupper($_POST['serial']);
$user=$_POST['inputname'];
$type='1';
$org='-1';
$control = "8670";
$now = new DateTime(null, new DateTimeZone('Europe/London'));
$date = $now->format('Y-m-d H:i:s');
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$dupe = sqlsrv_query($conn, "SELECT * FROM Asset WHERE Serial_Number = '$serial'");
$num_rows = sqlsrv_num_rows($dupe);
if ($num_rows == 0) {
$tsql = "INSERT INTO Asset (Name, Asset_Type_ID, Ref_Code, Owner_Organisation_ID, Make, Model, Serial_Number, Current_Location, Start_Date)
VALUES ('$desc', '$type', '$code', '$org', '$make', '$model', '$serial', '$user', '$date')";
sqlsrv_query( $conn, $tsql);
echo "Asset Uploaded";
} else {
echo 'Error! Already on our database!';
}
Any help to get this working is appreciated.
I replaced
$dupe = sqlsrv_query($conn, "SELECT Serial_Number FROM Asset WHERE Serial_Number = '$serial'");
with
$dupe = sqlsrv_query($conn, "SELECT Serial_Number FROM Asset WHERE Serial_Number = '$serial'", array(), array("Scrollable"=>"buffered"));
and it worked perfectly.
Thanks to those who helped me figure out where the code was going wrong.
I just want to add an employee and after that, the employee ID will also increment. Also that textbox must be disabled
Also here's my code. All I want is to auto increment my employee ID when I add a new employee. I hope everyone will help me. Thank you in advance. :)
<center>
<form class="contact_form" action="#" method="post">
<h2>Register New Employee</h2>
<br/>
<table>
<tr>
<td><label for="emp">Emp ID:</label></td>
<td><input type="text" name="emp" placeholder="Emp ID" required /></td>
</tr>
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" name="fname" placeholder="First Name" required />
<input type="text" name="lname" placeholder="Last Name" required /></td>
</tr>
<tr>
<td><label for="address">Address:</label></td>
<td><input type="text" name="address" placeholder="Full Address" required /></td>
</tr>
<tr>
<td><label for="contact">Contact:</label></td>
<td><input type="text" name="contact" placeholder="Contact Number" required /></td>
</tr>
<tr>
<td><label for="type">Type:</label></td>
<td><select name="type" id="type">
<option>Type of Employee</option>
<option>Contractual</option>
<option>Regular</option>
</select>
</td>
</tr>
<tr>
<td><label for="salary">Salary:</label></td>
<td><input type="text" name="salary" placeholder="Emp Salary" required /></td>
</tr>
</table>
<br/>
<button class="submit" name="submit" type="submit" onclick="message()">Submit</button>
<button class="reset" name="reset" type="reset">Clear</button>
</form>
<?php
if (isset($_POST['submit'])) {
include 'alqdb.php';
$emp=$_POST['emp'];
$fname= $_POST['fname'];
$lname=$_POST['lname'];
$address=$_POST['address'];
$contact=$_POST['contact'];
$type=$_POST['type'];
$salary=$_POST['salary'];
mysqli_query($con, "INSERT INTO employee (EmpID,EmpFName,EmpLName,EmpAddress,ContactNumber,TypeofEmployee,Salary)
VALUES ('$emp','$fname','$lname','$address','$contact','$type','$salary')");
}
?>
</center>
</body>
<script language="javascript">
function message() {
alert("Successfully added!");
}
</script>
If you want to have an EmpID like EMP001
this code will work:
public function autoincemp()
{
global $value2;
$query = "SELECT empid from tbemployee order by empid desc LIMIT 1";
$stmt = $this->db->prepare($query);
$stmt->execute();
if ($stmt->rowCount() > 0) {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$value2 = $row['empid'];
$value2 = substr($value2, 3, 5);
$value2 = (int) $value2 + 1;
$value2 = "EMP" . sprintf('%04s', $value2);
$value = $value2;
return $value;
} else {
$value2 = "EMP0001";
$value = $value2;
return $value;
}
}
You could modify your database to include AUTO_INCREMENT in EmpID.
You can disable input by doing <input type="text" name="emp" placeholder="Emp ID" required disabled />
Place AUTO_INCREMENT attribute to emp_id column in your DB. Remove that EMP ID field from your UI.
The AUTO_INCREMENT attribute can be used to generate a unique identity for new rows. Means, AUTO_INCREMENT automatically insert new incremented id for that field on each INSERT query
Reference
You can hide Emp ID code and change input type="text" to input type="hidden" and remove required in your form.
Now just use AUTO_INCREMENT for EmpId in your table.
It's late but you can do this,
$id = 1; //Your last record Id + 1
str_pad($id, 3, "0", STR_PAD_LEFT);
Hope this helps someone.
Reference
REATE TABLE dbo.tblUsers
(ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into tblUsers without specifying values for ID or UserID:
INSERT INTO dbo.tblUsersCol1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
The data inserts into the first table, but the code for getting the ID numbers doesn't seem to work, and the data is not inserted into the next two tables.
The code runs and the Thank you message appears thanking the person for submitting their details.
There are three pages of code. The connect code is in one file. The processing code file and the form file.
I won't include the connect code here, because it works.
Here is the form code:
enter code here
<form method="post" action="formprocess3.php">
<table>
<tr>
<td>Customer Details</td>
<td>Appointment Preference</td>
<td>Cupcake Details</td>
</tr>
<tr>
<td>First Name
<input name="FirstName" type="text" id="FirstName" maxlength="20" value="<?php if (isset($_POST['FirstName'])) echo $_POST ['FirstName']; ?>"/>
</td>
<td>Appointment Date
<input name="AppointmentDate" type="date" id="AppointmentDate" maxlength="10" value="<?php if (isset($_POST['AppointmentDate'])) echo $_POST['AppointmentDate']; ?>"/>
</td>
<td>Size
<select name="CupcakeSize" id="CupcakeSize" type="radio" maxlength="5" value="<?php if (isset($_POST['CupcakeSize'])) echo $_POST['CupcakeSize']; ?>"/>
<option></option>
<option>Small</option>
<option>Large</option>
</select></td>
</tr>
<tr>
<td>Surname
<input name="Surname" type="text" id="Surname" maxlength="20" value="<?php if (isset($_POST['Surame'])) echo $_POST['Surname']; ?>"/></td>
<td>Appointment Time
<select name="AppointmentTime" type="radio" maxlength="20" value="<?php if (isset($_POST['AppointmentTime'])) echo $_POST ['AppointmentTime']; ?>"/>
<option></option>
<option>9.30am -10.30am</option>
<option>11am - 12pm</option>
<option>1.30pm - 2.30pm</option>
<option>3pm - 4pm</option>
<option>4.30pm - 5.30pm</option>
<option>7pm - 8pm</option>
</select>
</td>
<td>Quantity
<input type="text" name="Quantity" id="Quantity"/></td>
</tr>
<tr>
<td>Email address
<input name="EmailAddress" type="email" id="Email" maxlength="20" value="<?php if (isset($_POST['EmailAddress'])) echo $_POST['EmailAddress']; ?>"/></td>
<td>Taster
<input name="Taster" type="checkbox" id="Taster"/>
</td>
<td maxlength="1" type="radio" value="<?php if (isset($_POST['Taster'])) echo $_POST['Taster']; ?>"/>
<td>Frosting
<select name="CupcakeFrosting" id="CupcakeFrosting" type="radio" maxlength="10" value="<?php if (isset($_POST['CupcakeFrosting'])) echo $_POST['CupcakeFrosting']; ?>"/>
<option></option>
<option>Strawberry</option>
<option>Chocolate</option>
<option>Vanilla</option>
<option>Coffee</option>
<option>Orange</option>
<option>Blue</option>
<option>Pink</option>
<option>Green</option>
<option>Red</option>
<option>Purple</option>
</select></td>
</tr>
<tr>
<td>Postcode
<input name="Postcode" type="text" id="Postcode" style="width: 130px; height: 20px" class="auto-style24" maxlength="10" value="<?php if (isset($_POST['Postcode'])) echo $_POST['Postcode']; ?>"/></td>
<td>Cake wanted by
<input name="CakeWantedBy" type="date" id="CakeWantedBy" maxlength="10" value="<?php if (isset($_POST['CakeWantedBy'])) echo $_POST['CakeWantedBy']; ?>"/>
</td>
<td>
<select name="CupcakeFlavour" id="Flavour" type="radio" maxlength="10" value="<?php if (isset($_POST['CupcakeFlavour'])) echo $_POST['CupcakeFlavour']; ?>"/>
<option></option>
<option>Banana</option>
<option>Caramel</option>
<option>Carrot</option>
<option>Chocolate</option>
<option>Vanilla</option>
<option>Red Velvet</option>
<option>Oreo</option>
<option>Coffee</option>
<option>Decide with taster £20</option>
</select></td>
</tr>
<tr>
<td>
<input name="MobileNumber" type="text" id="MobileNumber" maxlength="20" value="<?php if (isset($_POST['MobileNumber'])) echo $_POST['MobileNumber']; ?>"/>
</td>
<td>
<span class="auto-style24">Occasion
<select name="Occasion" type="radio" id="Occasion" maxlength="20" value="<?php if (isset($_POST['Occassion'])) echo $_POST['Occassion']; ?>"/>
<option></option>
<option>New baby</option>
<option>Birthday</option>
<option>Wedding</option>
<option>New Job</option>
<option>Christmas</option>
<option>Easter</option>
<option>Valentines</option>
<option>Congratulations</option>
<option>Anniversary</option>
<option>Other</option>
</select></td>
</tr>
</table>
</form>
The code for inserting the form data into the three database tables:
<html>
<head>
<title>Form Process Message</title>
</head><body>
<?php #
// This script performs an INSERT query to add a record to the users table.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// open the database...
require ('mysqli_connect.php');
// Make the query:
// Customer details
$t = $_POST[Title];
$fn = $_POST[FirstName];
$sn = $_POST[Surname];
$e = $_POST[EmailAddress];
$ht = $_POST[HomeTelephone];
$mn = $_POST[MobileNumber];
$hn = $_POST[HouseNumberName];
$s = $_POST[Street];
$tw = $_POST[Town];
$c = $_POST[County];
$pc = $_POST[Postcode];
// Cake details
$ct = $POST[CupcakeType];
$cn = $_POST[CupcakeNumber];
$cf = $_POST[CupcakeFrosting];
$o = $_POST[Occassion];
// Preferred Appointment
$ad = $_POST[AppointmentDate];
$at = $_POST[AppointmentTime];
$ta = $_POST[Taster];
$cwb = $_POST[CakeWantedBy];
$q = "INSERT INTO customerdetails(Title, FirstName, Surname, EmailAddress, HomeTelephone, MobileNumber, HouseNumberName, Street, Town, County, Postcode) VALUES ('$t','$fn', '$sn', '$e', '$ht', '$mn', '$hn', '$s', '$tw', '$c', '$pc')";
//execute query
$r = #mysqli_query ($dbc, $q);
//get customer id for preferred appointment
$ci = my_sqli_insert_id($dbc);
$q1 = "INSERT INTO cakedetail(CupcakeType, CupcakeNumber, CupcakeFrosting, Occassion) VALUES ('$ct','$cn', '$cf', '$o')";
//execute query
$r1 = #mysqli_query ($dbc, $q1);
//get cakedetail id for preferred appointment
$cdi = my_sqli_insert_id($dbc);
$q2 = "INSERT INTO preferredappointment(AppointmentDate, AppoitmentTime, Taster, CakeWantedBy, EmailAddress) VALUES ($ci, $cdi, '$ad','$at', '$ta', '$cwb', '$e')";
//execute query
$r2 = #mysqli_query ($dbc, $q2);
// Run the query.
if ($r) {
// If it ran OK.
// Print a message:
echo '<h1>Thank you!
<br />
Your request is now registered.
<br />
Back to the Gallery page</h1>';
}
else {
// If it did not run OK.
// Public message:
echo '<h1>System Error</h1>
<p class="error">You could not be registered due to a system error. We apologise for any inconvenience.</p>
Back to the Gallery page';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />
Query: ' . $q . '</p>';
}
//close the dbc
mysqli_close($dbc);
}
?>
</body>
</html>
There are three database tables called cakeorder, customerdetails and preferred appointment.
I don't think the multiple table insert works with earlier versions PHP, which is what I was using to start with, but I am now using xampp 5.5.24 and PHP 5.5.24.
I stripped out most the formatting of the html, so I may have left a hanging tag somewhere here, but there isn't one on the actual web page.
I am not very proficient in PHP, so a lot of this is put together from looking through this website.
Any help would be gratefully received.
Thank you
Thank you for your feedback. It's not for professional use, so I am not so worried about vulnerability it is just trying to get the stuff to work. As I said I don't know much about php code hence the mistake of using my_sqli_insert_id. It may be better to create a stored procedure, but I am just learning the basics at the moment.