Inserting multiple rows into MySQL at once - php

I am trying to submit a table full of information at once, and cannot find the answer. It has no problem submitting one set of information to the DB, but i need to insult between 1 and 50 of the same value at once. Here is an example:
We are recording lap times, therefore we need to be able to fill in a table on a web app, with loads of names, and event times. Therefore, we will need to add loads of SQL entries at once.
I have tried just copy and pasting the form info, but this results in a blank set of data in phpmyadmin.
Here is the code:
<?php
$host = "localhost";
$databasename = "pe_results";
$databaseusername = "root";
$databasepassword = "";
$conn = mysql_connect("$host", "$databaseusername", "$databasepassword");
mysql_select_db("$databasename", $conn);
if (isset($_POST['Name'])) {
$Name = $_POST['Name'];
}
if (isset($_POST['Short'])) {
$Short = $_POST['Short'];
}
if (isset($_POST['Med'])) {
$Med = $_POST['Med'];
}
if (isset($_POST['Long'])) {
$Long = $_POST['Long'];
}
if (isset($_POST['VLong'])) {
$VLong = $_POST['VLong'];
}
if (isset($_POST['Extreme'])) {
$Extreme = $_POST['Extreme'];
}
if (isset($_POST['LJump'])) {
$LJump = $_POST['LJump'];
}
if (isset($_POST['HJump'])) {
$HJump = $_POST['HJump'];
}
if (isset($_POST['Shotputt'])) {
$Shotputt = $_POST['Shotputt'];
}
if (isset($_POST['Discuss'])) {
$Discuss = $_POST['Discuss'];
}
if (isset($_POST['Javelin'])) {
$Javelin = $_POST['Javelin'];
}
if (isset($_POST['Date'])) {
$Date = $_POST['Date'];
}
if (isset($_POST['Year'])) {
$Year = $_POST['Year'];
}
$i = count($Name);
for ($i=0;$i<10;$i++) {
$n = $Name[$i];
$s = $Short[$i];
$me = $Med[$i];
$lng = $Long[$i];
$slng = $VLong[$i];
$ext = $Extreme[$i];
$ljump = $LJump[$i];
$hjump = $HJump[$i];
$shot = $Shotputt[$i];
$disc = $Discuss[$i];
$jav = $Javelin[$i];
$date = $Date[$i];
$year = $Year[$i];
//and so on with more variable...
$sql="INSERT INTO results_main (`Name`, `Short`, `Med`, `Long`, `Vlong`, `Extreme`, `LJump`, `HJump`, `Shotputt`, `Discuss`, `Javelin`, `Date`, `Year`)
VALUES ('$n', '$s', '$me', '$lng', '$slng', '$ext', '$ljump', '$hjump', '$shot', '$disc', '$jav', '$date', '$year')";
}
$result = mysql_query($sql) or die(mysql_error ());;
if($result){
echo"<br/>Everythings been saved";
echo "<BR>";
echo "<a href='index.php'>Back to the main page</a>";
}
else {
echo $result = mysql_query($sql,$conn) or die (mysql_error ());
}
// close connection
mysql_close($conn);
?>
Also find HTML below
<?php
// Create connection
$con=mysqli_connect("127.0.0.1","root","","pe_results");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Uh oh, tell chris that " . mysqli_connect_error() . "NO DATA WILL BE SAVED";
}
?>
<div id="1" >Results</div>
<div id="2">Record</div>
<div id="3">Overview</div>
<div id="4">Blank</div>
<form name="input_primary" action="process.php" method="post">
<font color="#FFFFFF"><strong>Date:</strong></font><input name="Date" type="date" />
<font color="#FFFFFF"><strong>Year:</strong></font><select name="Year">
<option value="7">Year 7</option>
<option value="8">Year 8</option>
<option value="9">Year 9</option>
<option value="10">Year 10</option>
<option value="11">Year 11</option>
<option value="12">Year 12</option>
<option value="13">Year 13</option>
</select>
<input type="submit" value="Save results!" name="submit" />
<table width="200" border="1px solid black" id="maintab">
<tr>
<th scope="col">Name</th>
<th scope="col">100m</th>
<th scope="col">200m</th>
<th scope="col">400m</th>
<th scope="col">800m</th>
<th scope="col">1500m</th>
<th scope="col">Long Jump</th>
<th scope="col">High Jump</th>
<th scope="col">Shotputt</th>
<th scope="col">Discus</th>
<th scope="col">Javelin</th>
</tr>
<tr>
<td>
<input name="Name" type="text" />
</td>
<td>
<input name="Short" type="text" size="10px" />
</td>
<td>
<input name="Med" type="text" size="10px" />
</td>
<td>
<input name="Long" type="text" size="10px" />
</td>
<td>
<input name="VLong" type="text" size="10px" />
</td>
<td>
<input name="Extreme" type="text" size="10px" />
</td>
<td>
<input name="LJump" type="text" size="10px" />
</td>
<td>
<input name="HJump" type="text" size="10px" />
</td>
<td>
<input name="Shotputt" type="text" size="10px" />
</td>
<td>
<input name="Discuss" type="text" size="10px" />
</td>
<td>
<input name="Javelin" type="text" size="10px" />
</td>
</tr>

If I understood your Question right what you wanna do is name the fields with a []
So
<select name="Year">
Becomes
<select name="Year[]">
Then you'll be able to loop through the submitted values, example:
foreach($_POST['Year'] as $k=>$v){
echo $v." - This is the value";
echo $k." - This is the key";
}
EDIT:
(string)$insert;
if(is_array($_POST['Year'])){
foreach($_POST['Year'] as $k=>$v){
$insert .= "(".$_POST['Name'][$k].", ".$_POST['Short'][$k].", ".$_POST['Med'][$k].", ".$_POST['Long'][$k].", ".$_POST['VLong'][$k].", ".$_POST['Extreme'][$k].", ".$_POST['LJump'][$k].", ".$_POST['HJump'][$k].", ".$_POST['Shotputt'][$k].", ".$_POST['Discuss'][$k].", ".$_POST['Javelin'][$k].", ".$_POST['Date'][$k].", ".$_POST['Year'][$k]."),";
}
$insert = substr_replace($insert ,0,-1);
}else{
$insert .= "($_POST['Name'], $_POST['Short'], $_POST['Med'], $_POST['Long'], $_POST['VLong'], $_POST['Extreme'], $_POST['LJump'], $_POST['HJump'], $_POST['Shotputt'], $_POST['Discuss'], $_POST['Javelin'], $_POST['Date'], $_POST['Year'])";
}
$sql="INSERT INTO results_main
(`Name`, `Short`, `Med`, `Long`, `VLong`, `Extreme`, `LJump`, `HJump`, `Shotputt`, `Discuss`, `Javelin`, `Date`, `Year`)
VALUES
".$insert;
This should do the trick to get everything into only one query instead of doing multiple queries for each row

Add brackets [] to ALL your names in your html-form (where it makes sense). The bracket [] tells that elements are treated as dynamic arrays.
In your html-form, do something like this:
<form name="input_primary" action="process.php" method="post">
<font color="#FFFFFF"><strong>Date:</strong></font><input name="Date" type="date" />
<font color="#FFFFFF"><strong>Year:</strong></font><select name="Year">
<option value="7">Year 7</option>
<option value="8">Year 8</option>
<option value="9">Year 9</option>
<option value="10">Year 10</option>
<option value="11">Year 11</option>
<option value="12">Year 12</option>
<option value="13">Year 13</option>
</select>
<input type="submit" value="Save results!" name="submit" />
<table width="200" border="1px solid black" id="maintab">
<tr>
<th scope="col">Name</th>
<th scope="col">100m</th>
<th scope="col">200m</th>
<th scope="col">400m</th>
<th scope="col">800m</th>
<th scope="col">1500m</th>
<th scope="col">Long Jump</th>
<th scope="col">High Jump</th>
<th scope="col">Shotputt</th>
<th scope="col">Discus</th>
<th scope="col">Javelin</th>
</tr>
<?php
//Repeat element inside loop 10 times
for($i=0;$i<10;$i++) {
?>
<tr>
<td>
<input name="Name[]" type="text" />
</td>
<td>
<input name="Short[]" type="text" size="10px" />
</td>
<td>
<input name="Med[]" type="text" size="10px" />
</td>
<td>
<input name="Long[]" type="text" size="10px" />
</td>
<td>
<input name="VLong[]" type="text" size="10px" />
</td>
<td>
<input name="Extreme[]" type="text" size="10px" />
</td>
<td>
<input name="LJump[]" type="text" size="10px" />
</td>
<td>
<input name="HJump[]" type="text" size="10px" />
</td>
<td>
<input name="Shotputt[]" type="text" size="10px" />
</td>
<td>
<input name="Discuss[]" type="text" size="10px" />
</td>
<td>
<input name="Javelin[]" type="text" size="10px" />
</td>
</tr>
<?php
}
?>
</table>
</form>
And in your PHP code do something like this:
//Create initial query for sql-insert.
$sql="INSERT INTO results_main (`Name`, `Short`, `Med`, `Long`, `Vlong`, `Extreme`, `LJump`, `HJump`, `Shotputt`, `Discuss`, `Javelin`, `Date`, `Year`) VALUES ";
$date = $Date; //Do like this if date-element is only occur once (at top) (then no need for brackets)
$year = $Year; //Do like this if year-element is only occur once (at top) (then no need for brackets)
$cnt = count($Name);
for ($i=0;$i<$cnt;$i++) {
//Use mysql_escape_string to escape strings (when needed) BEFORE adding to the $sql.
$n = $Name[$i];
$s = $Short[$i];
$me = $Med[$i];
$lng = $Long[$i];
$slng = $VLong[$i];
$ext = $Extreme[$i];
$ljump = $LJump[$i];
$hjump = $HJump[$i];
$shot = $Shotputt[$i];
$disc = $Discuss[$i];
$jav = $Javelin[$i];
//Insert each row separated with a comma
$sql .= "('$n', '$s', '$me', '$lng', '$slng', '$ext', '$ljump', '$hjump', '$shot', '$disc', '$jav', '$date', '$year'),";
}
$useQuery = substr($sql, 0, -1); //Delete last comma
$result = mysql_query($useQuery); //Do the actual insert
then of course, read up on PDO instead of using mysql_query etc. Do this soon because mysql_* functions like this are deprecated and will be removed in the future. PDO is a better alternative because it's oop, it's safer and more flexible. Start from here... http://www.php.net/manual/en/intro.pdo.php

Storing your data across multiple arrays is unsafe because its so easy to get out of order and cause errors. Instead store data into an associative array like this:
$people = array();
$people[] = array('Name' => $name, 'Short' => $short ....);
The above code creates and array of arrays and the inner arrays are associative arrays so you can use the following syntax to get the name of the first person:
$people[0]['Name'];
Everything stays together and if certain values arn't set for certain people it will not seep into the other peoples records.
I see you were using POST variables. The above associative array can be easily passed around with ajax (if thats what your using, just an option) by using json_encode and json_decode. This helps preserve data structures when your passing it through multiple languages.
Lastly to insert a large number of records I would suggest a PDO statement as one ofthe easiest and cleanest way to do this. Check out a great tutorial here http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
Hope this helps, good luck!

Related

How to insert multiple row to new table using single submit button

I am try to inset multiple rows to new table fetched from other table, but problem is that only last single row is being inserted and no other now is getting insert, so please tell the issue where i am lacking
<?php
error_reporting(1);
session_start();
$s=$_SESSION['username'];
//connect database
$con=mysql_connect("localhost","root","") or die(mysql_error());
// select database
mysql_select_db("education",$con);
$date= date("Y/m/d");
//select all values from empInfo table
$data="SELECT * FROM student";
$val=mysql_query($data);
?>
<html>
<body>
<table>
</table>
<form action="submit.php" method="post" >
<table>
<tr>
<th>Teacher name</th>
<th>Date</th>
<th>Roll No</th>
<th>Student name</th>
<th>Father name</th>
<th>Addhaar No</th>
<th>Status(P)</th>
<th>Status(A)</th>
<th>Status(L)</th>
</tr>
<?php while($r=mysql_fetch_array($val))
{?>
<tr style="border:2px solid black;">
<td><input type="text" name="teacher" value="
<?php echo $s; ?>"></td>
<td><input type="text" name="date" value="
<?php echo $date; ?>"></td>
<td ><input name="roll_no" value="
<?php echo $r['roll_no']; ?>">
</td>
<td><input name="student_name" value="
<?php echo $r['student_name'] ?>">
</td>
<td><input name="father_name" value="
<?php echo $r['father_name'] ?>">
</td>
<td>
<input name="addhaar_no" value="
<?php echo $r['addhaar_no'] ?>">
</td>
<td>
<input type="checkbox" value="present" name="status"> Present
</td>
<td>
<input type="checkbox" name="status" value="absent">Absent
</td>
<td>
<input type="checkbox" name="status" value="leave">Leave
</td>
</tr>
</table>
<?
}
?>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
submit.php -
<?php
error_reporting(1);
$con=mysql_connect("localhost","root","") or die(mysql_error());
// select database
mysql_select_db("education",$con);
//get data from html form
$roll_no=$_POST['roll_no'];
$student_name=$_POST['student_name'];
$father_name=$_POST['father_name'];
$addhaar_no=$_POST['addhaar_no'];
$status=$_POST['status'];
//Insert values in empInfo table with column name
$query="INSERT INTO attandance
VALUES ('', '$roll_no','$student_name','$father_name','$addhaar_no','$status'),
VALUES ('', '$roll_no','$student_name','$father_name','$addhaar_no','$status')";
echo $query;
die();
mysql_query($query);
?>
page
You need to have unique name for each fields. What you can do is have a counter in loop and add it the names of the fields to make it unique.
Sample:
$ctr = 0;
while($r=mysql_fetch_array($val)){
echo "<input type="text" name='teacher_".$ctr."'>";
$ctr++;
}
Or make the names array, and loop through the values in saving the data.
while($r=mysql_fetch_array($val)){
echo "<input type="text" name='teacher[]'>";
}
I think you should study PHP a bit more... As i can see in your code, you haven't understood fundamentals of PHP.
1: Normally, you won't mix up HTML and PHP like you did in your first code. Its just confusing and really annoying to read the code later.
2: When you post your form, for example the variable $_POST['student_name']; will just contain the value of the last row (your problem). So, why? Because you can't assign more than one value to a variable. Or at least, not the way you tried it. Array would be a good keywoard for this problem.
3: Please check your SQL syntax... Thats why i'm saying you haven't understand fundamentals... http://www.w3schools.com/sql/sql_insert.asp
Why you're repeating your values? You think the second time the variables will contain the values of the next row? Thats just false. A Variable contains everytime the same value, as long as you don't assign a new value to it.
4: mysql is depracted. Use mysqli or PDO instead.
My tip: You need to have unique input names. Just take a look at PHP, how for/while loops work, study a bit more and try it again. It's not difficult to solve, but i think you'll learn a lot more if we don't give you the direct solution.
Now mysql is depracted. So, you can use mysqli or PDO instead.
I can use now PDO. Please follow bellow code carefully:
<?php
$user = 'root';
$pass = '';
$dbh = new PDO('mysql:host=localhost;dbname=education', $user, $pass);
try {
$select = $dbh->query('SELECT * from student');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
<html>
<body>
<form action="submit.php" method="post" >
<table>
<tr>
<th>Teacher name</th>
<th>Date</th>
<th>Roll No</th>
<th>Student name</th>
<th>Father name</th>
<th>Addhaar No</th>
<th>Status(P)</th>
<th>Status(A)</th>
<th>Status(L)</th>
</tr>
<?php
foreach($select as $val) {
?>
<tr style="border:2px solid black;">
<td><input type="text" name="teacher" value="<?php echo $s; ?>"></td>
<td><input type="text" name="date" value="<?php echo $date; ?>"></td>
<td><input name="roll_no" value="<?php echo $r['roll_no']; ?>"></td>
<td><input name="student_name" value="<?php echo $r['student_name'] ?>"></td>
<td><input name="father_name" value="<?php echo $r['father_name'] ?>"></td>
<td><input name="addhaar_no" value="<?php echo $r['addhaar_no'] ?>"></td>
<td><input type="checkbox" value="present" name="status"> Present</td>
<td><input type="checkbox" name="status" value="absent">Absent</td>
<td><input type="checkbox" name="status" value="leave">Leave</td>
</tr>
<?php
}
?>
</table>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
For submit.php code bellow
<?php
$user = 'root';
$pass = '';
$dbh = new PDO('mysql:host=localhost;dbname=education', $user, $pass);
$stmt = $dbh->prepare("INSERT INTO attandance (roll_no, student_name, father_name, addhaar_no, status) VALUES (?, ?, ?, ?, ?)");
$stmt->bindParam(1, $roll_no);
$stmt->bindParam(2, $student_name);
$stmt->bindParam(2, $father_name);
$stmt->bindParam(2, $addhaar_no);
$stmt->bindParam(2, $status);
//if you insert 2 time then
for($x=0; $x<2; $x++) {
$roll_no = $_POST['roll_no'];
$student_name = $_POST['student_name'];
$father_name = $_POST['father_name'];
$addhaar_no = $_POST['addhaar_no'];
$status = $_POST['status'];
$stmt->execute();
}
?>

adding multiple rows in mysql

I have a big problem that somebody is attacking me by adding multiple rows into my db. Hes using the form I have on my website. I got about 2500 rows in my db and all rows were different. Its been generating by any script. Do you have any suggestions how I can fix it? this is my form I have on my website
<?php
if(isset($_POST['type'])) {$type = mysql_real_escape_string($_POST['type']);}
if(isset($_POST['ip'])) {$ip = mysql_real_escape_string($_POST['ip']);}
if(isset($_POST['port'])) {$port = mysql_real_escape_string($_POST['port']);}
$add_date = time();
if(isset($_POST['email'])) {$email = mysql_real_escape_string($_POST['email']);}
if(isset($_POST['web'])) {$web = mysql_real_escape_string($_POST['web']);}
if(isset($_POST['mod'])) {$mod = mysql_real_escape_string($_POST['mod']);}
echo "
<form action='#' method='post'>
<legend>Formulár pre pridanie serveru</legend>
<table>
<tr>
<td>
Hra:
</td>
<td>
<select name='type'>
<option value='cs16'>Counter Strike 1.6</option>
<option value='source'>Counter Strike Source</option>
<option value='csgo'>Counter Strike Global Offensive</option>
</select>
(vyberte hru)
</td>
</tr>
<tr>
<td>
Typ:
</td>
<td>
<select name='mod'>";
$modes = mysql_query("SELECT * FROM `lgsl_modes`") or die(mysql_error());
while($modes_names = mysql_fetch_array($modes))
{
echo '<option value="'.$modes_names['mod'].'">'.$modes_names['name'].'</option>';
}
echo "</select>
(vyberte herný mód)
</td>
</tr>
<tr>
<td>
IP serveru:
</td>
<td>
<input type='text' name='ip' value='' required>
(iba číslice a bodky)
</td>
</tr>
<tr>
<td>
Port serveru:
</td>
<td>
<input type='text' name='port' value='' required>
(iba číslice)
</td>
</tr>
<tr>
<td>
Web serveru:
</td>
<td>
<input type='text' name='web' value='' required>
(uvádzajte bez začiatočného http://)
</td>
</tr>
<tr>
<td>
Váš email:
</td>
<td>
<input type='text' name='email' value='' required>
(kontaktný email)
</td>
</tr>
<tr>
<td>
<input type='submit' name='odoslat' value='Odoslať'>
</td>
</tr>
</table>
</form>
";
if($ip) if(!preg_match("/^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$/",$ip)) $usermsgip="Ip adresa bola uvedená v zlom tvare.";
if($port) if(!preg_match("/^[0-9]{5}$/",$port)) $usermsgport="Port bol uvedený v zlom tvare.";
if($email) if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/",$email)) $usermsgemail="Email bol uvedený v zlom tvare.";
if($web) if(!preg_match("%^((https?://)|(www\.))([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%i" ,$web)) $usermsgweb="Web bol uvedený v zlom tvare.";
if(isset($_POST['odoslat']) && $usermsgip || $usermsgport || $usermsgemail || $usermsgweb) {
if($usermsgip) echo $usermsgip."<br>";
if($usermsgport) echo $usermsgport."<br>";
if($usermsgemail) echo $usermsgemail."<br>";
if($usermsgweb) echo $usermsgweb."<br>";
}
if(isset($_POST['odoslat']) && !$usermsgip && !$usermsgport && !$usermsgemail && !$usermsgweb) {
$kontrola = mysql_query("SELECT * FROM `lgsl` WHERE `ip`='".$ip."' AND `c_port`=".$port);
if(mysql_num_rows($kontrola)) {echo "Server už bol pridaný do banlistu.";}
else {
mysql_query("INSERT INTO `lgsl` (`type`, `ip`, `c_port`, `q_port`, `disabled`, `add_date`, `email`, `web`, `mod`)
VALUES ('$type', '$ip', '$port', '$port', '1', '$add_date', '$email', '$web', '$mod')");
echo 'Server bol úspešne odoslaný na schválenie.';
}
}
?>
I think you should rewrite the whole script using PDO. With Pdo you can avoid SQL-Injection in easy way. Here's a link where you can find that and all the web is full of guide and examples.
Anyway if you want to fix your script you can use Captcha to avoid automatic form submit and a library to sanitize input.
Here you find a simple captcha example and a good sanitize library.
You can whatch here some good tips to solve problems.
Hope this helps.

Inserting data from a form to multiple tables in a mysql database using php

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.

assign data from one table to a specific table (group)

I have a classrooms in schools and when I click on a certain classroom, I want to add students into it but my actual code is doing something stupid. It adds a student but i can see the student in all classrooms, not just in the one that i added him into. So when Im in classroom number 1, I see a form in there, I can add a student there, ... see how it works here:
here is the code: http://www.xxxx.xx/projekt/
here is my code in file trieda.php
<table align="center"><tr><td>
<form action="vlozit2.php" method="post">
Meno: <input type="text" name="meno" placeholder="Janko" maxlength="15" required>
Priezvisko: <input type="text" name="priezvisko" placeholder="Hruška" maxlength="20" required>
<input type="hidden" name="id_triedy" value="<?= $trieda['id_triedy'] ?>" />
<input type="submit" name="submit" value="Pridať študenta do triedy">
</form>
</td></tr></table>
<?php
$result = mysqli_query($prip,"SELECT * FROM student ORDER BY meno");
while($student = mysqli_fetch_array($result))
{
echo "<br /><table cellspacing='1' cellpadding='1' class='tabulka1' align='center'><tr>";
echo "<td width='200'><a href='student.php?id_triedy=".$trieda['id_triedy']."".id_student=".$student['id_student']."'>".$student['meno']." ".$student['priezvisko']."</a></td>";
?>
<td width='300px' align='right' bgcolor="#fbfbfb">Zmazať</td>
</tr></table>
<?php
}
?>
here is vlozit2.php (a code that works for the form to add a student)
if(isset($_POST['submit']))
{
//meno a priezvisko
$student = $_POST['meno'];
$student = $_POST['priezvisko'];
$trieda = $_POST['id_triedy'];
//connect to the database
include 'config.php';
//insert results from the form input
$sql = "INSERT INTO student (meno, priezvisko, id_triedy) VALUES('$_POST[meno]', '$_POST[priezvisko]', '$_POST[id_triedy]')";
$add = "<table align='center'>
<tr>
<td> Študent bol úspešne pridaný do triedy. </td>
</tr>
<tr>
<td><a href='./trieda.php'><strong>Späť</strong></a></td>
</tr>
</table>";
$not_add = "<table align='center'>
<tr>
<td> Študent s týmto menom a priezviskom už je v tejto triede. </td>
</tr>
<tr>
<td><a href='./trieda.php'><strong>Späť</strong></a></td>
</tr>
</table>";
if (mysqli_query($prip, $sql)) {
echo $add;
}else{
echo $not_add;
}
mysqli_close($prip);
}
?>
Try to replace your part of code with these snipets:
1) in trieda.php
<form action="vlozit2.php?id_triedy=<?php echo $_GET["id_triedy"];?>" method="post">
Meno: <input type="text" name="meno" placeholder="Janko" maxlength="15" required>
Priezvisko: <input type="text" name="priezvisko" placeholder="Hruška" maxlength="20" required>
<input type="submit" name="submit" value="Pridať študenta do triedy">
</form>
2) in vlozit2.php
$student = $_POST['meno'];
$priezvisko = $_POST['priezvisko'];
$id_trieda = $_GET['id_triedy'];
and
$sql = "INSERT INTO student (meno, priezvisko, id_triedy) VALUES( '{$student}', '{$priezvisko}', {$id_trieda} )";
Hopefully you store your id_trieda as INT type.
In your vlozit2.php file is nothing about inserting of class id. So put
<input type="hidden" name="classId" value="<?= $trieda['id'] ?>" />
to your form and in vlozit2.php get this value from $_POST['classId'] and insert it with other students data or anywhere you want to have it.

Php form update in update the form

I am running while loop and fetch 3 records from database. and then update it on same page. Every record have submit button. But after edit when i submit the form it catchs the values of last record only and update other rows with the last record values. Please if somebody help me out i'll be very thankful. Remember it catches the exact (id) but the other parameters are only of last row.
<form method="post" action="">
<table width="700" border="1">
<tr><th><?php echo $_SESSION['teamtwo']; ?></th></tr>
<tr>
<th>Player Name</th>
<th>Runs</th>
<th>Edit</th>
<th>Save</th>
</tr>
<?php
$team = new DBConnection();
$condition = "WHERE teamname = '".$_SESSION['teamtwo']."' and datecreated = CURDATE()";
$sel_player = $team->SelectRecord(array("*"),"`match`","$condition");
//$sel_player = mysql_query("SELECT * FROM `match` WHERE teamname = '$team1' and datecreated = CURDATE()") or die(mysql_error());
while($get_player = mysql_fetch_array($sel_player))
{
$totalruns = $get_player['runs_bat'];
$totalballs = $get_player['ball_bat'];
#$strike = $totalruns / $totalballs * 100;
?>
<tr>
<td><input type="text" name="player_name" value="<?php echo $get_player['player_name']; ?>" disabled="disabled" /></td>
<td><input type="text" name="runs" value="<?php echo $get_player['runs_bat']; ?>" size="1" /></td>
<td><button>Edit</button></td>
<td><input type="submit" value="Save" name="team" /></td>
</tr>
<?php
} ?>
</table>
</form>
<?php } ?>
</div>
</div>
</body>
</html>
<?php
if(isset($_POST['team'])){
$runs = $_POST['runs'];
$balls = $_POST['ball'];
$object = new DBConnection();
$arr_Field=array("runs_bat","ball_bat","player_status","how_out","opposite_bowl","opposite_player","sr","overs","bowl_ball","runs_ball","extra","madien");
$arr_Values=array("$runs","$balls","$status","$how_out","$opposite_bowler","$opposite_player","$sr","$over","$bowls","$score","$extra","$madien");
$condition = "WHERE id = '".$_REQUEST['player']."'";
//echo $_REQUEST['player'];
//echo $runs.$balls;
$object->UpdateRecord("`match`",$arr_Field,$arr_Values,"$condition") or die(mysql_error());
//header("Location:extra.php?update");
}
the problem is you are having one form and when you submit the form it will submit the last rows values because you are having same name for all 3 rows inside 1 form.
Solution:-
Create form element inside the while loop and close it inside the while loop itself . Like this you will have 3 forms each for 3 rows.
Code Example:-
while($get_player = mysql_fetch_array($sel_player))
{
$totalruns = $get_player['runs_bat'];
$totalballs = $get_player['ball_bat'];
#$strike = $totalruns / $totalballs * 100;
?>
<form>
<tr>
<td><input type="text" name="player_name" value="<?php echo $get_player['player_name']; ?>" disabled="disabled" /></td>
<td><input type="text" name="runs" value="<?php echo $get_player['runs_bat']; ?>" size="1" /></td>
<td><button>Edit</button></td>
<td><input type="submit" value="Save" name="team" /></td>
</tr>
</form>
<?php
} ?>
1.
you need to make input array in while because name attribute is overwriting in loop
<td><input type="text" name="player_name[<?php echo $get_player['id']?>]" value="<?php echo $get_player['player_name']; ?>" disabled="disabled" /></td>
<td><input type="text" name="runs[<?php echo $get_player['id']?>]" value="<?php echo $get_player['runs_bat']; ?>" size="1" /></td>
2.
you have all text boxes mean if press submit button of one row, then also you will get all textboxes as php side so make hidden variable in form to get which button clicked
//write javascript in your page
<script>
function setPlayerId(id) {
document.getElementById('playerid').value=id;
}
</script>
//take hidden field into form
<input type='hidden' name='playerid' value='0'>
//write down onlick button event
<input type="submit" value="Save" name="team" onClick="setPlayerId('<?php <?php echo $get_player['id']?>?>')"/>
3.
Now in php you will get that as below
echo $_POST['player_name'][$_POST['playerid']];
// same way you can do your insert or update.
this code must work
<form method="post" action="">
<table width="700" border="1">
<tr><th><?php echo $_SESSION['teamtwo']; ?></th></tr>
<tr>
<th>Player Name</th>
<th>Runs</th>
<th>Edit</th>
<th>Save</th>
</tr>
<?php
$team = new DBConnection();
$condition = "WHERE teamname = '".$_SESSION['teamtwo']."' and datecreated = CURDATE()";
$sel_player = $team->SelectRecord(array("*"),"`match`","$condition");
//$sel_player = mysql_query("SELECT * FROM `match` WHERE teamname = '$team1' and datecreated = CURDATE()") or die(mysql_error());
while($get_player = mysql_fetch_array($sel_player))
{
$totalruns = $get_player['runs_bat'];
$totalballs = $get_player['ball_bat'];
#$strike = $totalruns / $totalballs * 100;
?>
<tr>
<td><input type="text" name="player_name" value="<?php echo $get_player['player_name']; ?>" disabled="disabled" /></td>
<td><input type="text" name="runs<?=$get_player['id']?>" value="<?php echo $get_player['runs_bat']; ?>" size="1" /></td>
// you didnt write this i added
<input type="text" name="ball<?=$get_player['id']?>" value="<?php echo $get_player['ball_bat']; ?>" size="1" />
<td><button>Edit</button></td>
<td><input type="submit" value="Save" name="team" /></td>
</tr>
<?php
} ?>
</table>
</form>
<?php } ?>
</div>
</div>
</body>
</html>
<?php
if(isset($_POST['team'])){
$runsname = 'runs'.$_GET['player'];
$ballsname = 'ball'.$_GET['player'];
$runs = $_POST[$runsname];
$balls = $_POST[$ballsname];
$object = new DBConnection();
$arr_Field=array("runs_bat","ball_bat","player_status","how_out","opposite_bowl","opposite_player","sr","overs","bowl_ball","runs_ball","extra","madien");
$arr_Values=array("$runs","$balls","$status","$how_out","$opposite_bowler","$opposite_player","$sr","$over","$bowls","$score","$extra","$madien");
$condition = "WHERE id = '".$_REQUEST['player']."'";
//echo $_REQUEST['player'];
//echo $runs.$balls;
$object->UpdateRecord("`match`",$arr_Field,$arr_Values,"$condition") or die(mysql_error());
//header("Location:extra.php?update");
}

Categories