I have a php file named "add_report" with a form inside it. All my inputs are running, i can input data into my database, but everytime I use the select-option. my database accepts it as null. Why is that?
This is my form "add_report.php"
<div class="wrapper">
<form action="add_report_backend.php" method="post">
<input type="hidden" name="id">
<label>Agency: </label> <input class="input1" type="text" name="agency" value="CAAP" required readonly><br>
<label>File Name: </label> <input class="input2" type="text" name="filename" placeholder="file.pdf/xlsx/xls/docx" required autofocus><br>
<label>File Type: </label> <select name="myselectbox">
<option name="myoption1" value="myoption1">pdf</option>
<option name="myoption2" value="myoption2">excel</option>
<option name="myoption3" value="myoption3">word</option>
</select><br>
<label>Date: </label> <input class="input4" type="Date" name="date" required><br>
<input class="submit-btn" type="submit" name="insert" value="Save">
</form>
</div>
And this another php file "add_report_backend.php"
<?php
if(isset($_POST['insert']))
{
try {
$pdoConnect = new PDO("mysql:host=localhost;dbname=annualdb","root","");
$pdoConnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $exc) {
echo $exc->getMessage();
exit();
}
$id = $_POST['id'];
$Agency = $_POST['agency'];
$FName = $_POST['filename'];
$FType = $_POST['filetype'];
$Date = $_POST['date'];
$pdoQuery = "INSERT INTO `company_report`(`agency`, `filename`, `filetype`, `date`) VALUES (:Agency,:FName,:FType,:Date)";
$pdoResult = $pdoConnect->prepare($pdoQuery);
$pdoExec = $pdoResult->execute(array(":Agency"=>$Agency,":FName"=>$FName,":FType"=>$FType, ":Date"=>$Date));
if($pdoExec)
{
$pdoQuery = 'SELECT * FROM company_report';
$pdoResult = $pdoConnect->prepare($pdoQuery);
$pdoResult->execute();
while ($row = $pdoResult->fetch()){
echo $row['id'] . " | " .$row['agency'] . " | " . $row['filename'] . " | " . $row['filetype'] . " | " . $row['date'];
}
header("Location: ../agencies/company.php");
exit;
} else {
echo 'Data Not Inserted';
}
}
$pdoConnect = null;
?>
The HTML name attribute and the $_POST name should be the same.
You need to change
$FType = $_POST['filetype'];
by
$FType = $_POST['myselectbox'];
Change $FType = $_POST['filetype']; to $FType = $_POST['myselectbox'];
Related
I am trying to pass variables from delivery.php to delivery-insert.php using HTTP POST. Upon submitting, no variables are passed in.
Below is the form in delivery.php
<form action="delivery-insert.php" method="post">
<div class="form-group">
<label>Delivery No.</label>
<input type="text" class="form-control" id="deliverynoinput" placeholder="D0" required> <br>
<label>Price</label>
<input type="number" class="form-control" id="deliverypriceinput" placeholder="0" required> <br>
<label>Quantity</label>
<input type="number" class="form-control" id="deliveryquantityinput" placeholder="0" required>
</div>
<div class="form-group">
<label for="selectTruckInput">Select Delivery Truck</label>
<select class="form-control" id="selectTruckInput">
<?php
foreach ($trucks as $i => $value) {
print "<option>" . $value . "</option>";
}
?>
</select>
</div>
<div class="form-group">
<label for="selectCustomerInput">Select Delivery Customer</label>
<select class="form-control" id="selectCustomerInput">
<?php
foreach ($customers as $i => $value) {
print "<option>" . $value . "</option>";
}
?>
</select>
</div>
<div class="form-group">
<label for="selectDriverInput">Select Delivery Driver</label>
<select class="form-control" id="selectDriverInput">
<?php
foreach ($drivers as $i => $value) {
print "<option>" . $value . "</option>";
}
?>
</select>
</div>
<input type="submit"/>
</form>
And below is delivery-insert.php where I attempt to gather the POST variables.
<html>
<body>
<?php
$host = "localhost";
$user = "root";
$pw = "root";
$db = "project";
$con = new mysqli($host, $user, $pw, $db);
if (! $con) {
die("Connection failed: " . mysqli_connect_error());
}
$dno = $_POST['deliverynoinput'];
$dprice = intval($_POST['deliverypriceinput']);
$dquant = intval($_POST['deliveryquantityinput']);
$dtruck = $_POST['selectTruckInput'];
$dcust = $_POST['selectCustomerInput'];
$ddriver = $_POST['selectDriverInput'];
print '<h1>Here</h1>';
print '<h1>'.$dno.'</h1>';
print $_POST['selectTruckInput'];
$sql = "INSERT INTO delivery (deliveryno, price, truckid, custphoneno, driverid) VALUES ('$dno','$dprice','$dtruck','$dcust','$ddriver')";
if (mysqli_query($con, $sql)) {
print "added to delivery successfully";
} else {
print "Error: " . mysqli_error($con);
}
$sql = "INSERT INTO deliveryquantity (deliveryno, quantity) VALUES ('$dno', '$dquant')";
if (mysqli_query($con, $sql)) {
print "added to deliveryquantity successfully";
} else {
print "Error: " . mysqli_error($con);
}
$con->close();
?>
</body>
</html>
Does anyone know why all my variables are empty?
You will need the attribute name on your inputs. With this the browser will send the corresponding names as a key for $_POST. This even works for arrays!
e. g.
<!-- Single Value -->
<input name="someValue" />
<!-- Array -->
<input name="someArray[]" />
<input name="someArray[]" />
can be accessed like this:
// Single value
$_POST['someValue']
// Array
$_POST['someArray'][$numericIndex]
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I can not for the life of me figure out why the info i enter in from the form when it runs, will not enter into the database that i have linked to it. The info from the database shows up when I manually put it in, and the delete button works to erase the section of the database, but adding things doesnt work using the php form. Please help!
<?php
// A simple PHP script demonstrating how to connect to MySQL.
$servername = getenv('IP');
$username = getenv('C9_USER');
$password = "potato12";
$database = "c9";
$dbport = 3306;
// Create connection
$db = new mysqli($servername, $username, $password, $database, $dbport);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
echo "Connected successfully (".$db->host_info.")";
$thisPHP = $_SERVER['PHP_SELF'];
echo <<<EOT
<form action="$thisPHP" method="POST">
Name: <input type="text" name="Name"> Address: <input type="text" name="Address"><br>
Phone: <input type="text" name="Phone"> Email: <input type="text" name="Email"><br>
Availability: <input type="Radio" name="Availability" Value="Now"> Now(<1 month) <input type="Radio" name="Availability" value="Soon"> Soon(1-3 months) <input type="Radio" name="Availability" value="Exploring"> Exploring(3+ months)<br>
Company Title: <input type="text" name="Title"><br>
Job Title: <input type="text" name="Job Title"><br>
Description: <input type="text" name="Description"><br>
Skill 1 <select name="Skill1">
<option>Organized</option><option>Works in a team</option><option>Problem Solving</option>
</select>
Skill 2 <select name="Skill2">
<option>Organized</option><option>Works in a team</option><option>Problem Solving</option></select>
Skill 3 <select name="Skill3">
<option>Organized</option><option>Works in a team</option><option>Problem Solving</option></select><br>
Experiance <select name="Experiance">
<option>0</option><option>1-3</option><option>3-5</option><option>5-10</option><option>10+</option></select><br>
Position: <input type="radio" name="Position" value="Team-Member"> Team-Member <input type="radio" name="Position" value="Team-Leader"> Team-Leader <input type="radio" name="Position" value="Manager"> Manager <input type="radio" name="Position" value="Executive"> Executive <br>
<input type="submit" name="Add" value="Add"> <br>
<hr>
</form>
EOT;
// Start executing the script
$id = $_POST["ID"];
$Name = $_POST["Name"];
$Email = $_POST["Email"];
$Phone = $_POST["Phone"];
$Address = $_POST["Address"];
$Availability = $_POST["Availability"];
$Ctitle = $_POST["Title"];
$Jtitle = $_POST["Job Title"];
$Description = $_POST["Description"];
$Skill1 = $_POST["Skill1"];
$Skill2 = $_POST["Skill2"];
$Skill3 = $_POST["Skill3"];
$Experiance = $_POST["Experiance"];
$Position = $_POST["Position"];
// At least name must be specified
if (!empty($name)){
// Form sql string
$sql = "insert into Employee (ID, Name, Phone, Email, Address, Availability, Title, Job Title, Description, Skill1, Skill2, Skill3, Experiance, Position ) values ('$id', '$Name', '$Phone', '$Email', '$Address' , '$Availability' , '$Ctitle' , '$Jtitle' , '$Description' , '$Skill1' , '$Skill2' , '$Skill3', '$Experiance' , '$Position')";
if ($db->query ($sql) == TRUE)
{
echo "Record added <br>";
}
}
// Check if delete is selected
if (isset($_POST['btnDelete'])) {
$gid = $_POST['gid'];
$sql = "delete from Employee where id='$id'";
if ($db->query ($sql) == TRUE)
{
echo "Record deleted <br>";
}
}
else if (isset($_POST['btnEdit'])) {
$sql = "select * from Employee where id='$id'";
if (($result = $db->query ($sql)) == TRUE)
{
while($row = $result->fetch_assoc()) {
$id = $_POST["ID"];
$Name = $_POST["Name"];
$Email = $_POST["Email"];
$Phone = $_POST["Phone"];
$Address = $_POST["Address"];
$Availability = $_POST["Availability"];
$Ctitle = $_POST["title"];
$Jtitle = $_POST["Job Title"];
$Description = $_POST["Description"];
$Skill1 = $_POST["Skill1"];
$Skill2 = $_POST["Skill2"];
$Skill3 = $_POST["Skill3"];
$Experiance = $_POST["Experiance"];
}
}
echo <<<EOE
<form action="$thisPHP" method="POST">
Name: <input type="text" name="name"> Address: <input type="text" name="Address"><br>
Phone: <input type="text" name="phone"> Email: <input type="text" name="email"><br>
Availability: <input type="Radio" name="Availability" Value="Now"> Now(<1 month) <input type="Radio" name="Availability" value="Soon"> Soon(1-3 months) <input type="Radio" name="Availability" value="Exploring"> Exploring(3+ months)<br>
Company Title: <input type="text" name="title"><br>
Job Title: <input type="text" name="Job Title"><br>
Description: <input type="text" name="description"><br>
Skill 1 <select name="skill1">
<option>Organized</option><option>Works in a team</option><option>Problem Solving</option>
</select>
Skill 2 <select name="skill2">
<option>Organized</option><option>Works in a team</option><option>Problem Solving</option></select>
Skill 3 <select name="skill3">
<option>Organized</option><option>Works in a team</option><option>Problem Solving</option></select><br>
Experiance <select name="experiance">
<option>0</option><option>1-3</option><option>3-5</option><option>5-10</option><option>10+</option></select><br>
Position: <input type="radio" name=Position" value="Team-Member"> Team-Member <input type="radio" name=Position" value="Team-Leader"> Team-Leader <input type="radio" name=Position" value="Manager"> Manager <input type="radio" name=Position" value="Executive"> Executive <br>
<input type="submit" name="Add" value="Add"> <br>
<hr>
</form>
EOE;
}
// Show rows
$sql = "SELECT * FROM Employee";
$result = $db->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc())
{
$id = $row["ID"];
echo
"id: " . $id . " - Name: " . $row["Name"] .
" - Email: " . $row["Email"] .
" - Phone: " . $row["Phone"] .
" - Address: " . $row["Address"] .
" - Availability: " . $row["Availability"] .
" - Company Title: " . $row["Company Title"] .
" - Job Title: " . $row["Job Title"] .
" - Description: " . $row["Description"] .
" - Skill 1: " . $row["Skill1"] .
" - Skill 2: " . $row["Skill2"] .
" - Skill 3: " . $row["Skill3"] .
" - Experiance: " . $row["Experiance"];
echo " <form action=\"$thisPHP\" method='post' style=\"display:inline\" >";
echo "<input type='hidden' name='id' value='$id'>";
echo "<input type='submit' name='btnEdit' value='Edit'> ";
echo "<input type='submit' name='btnDelete' value='Delete'> </form>" . "<br>";
}
} else
{
echo "0 results";
}
$db->close();
?>
I am working on a project and would like to give the user per-determined values when updating a record.
Here is my code so far.
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>School Name:</strong> <input type="text" name="Name" value="<?php echo $Name; ?>"/><br/><br>
<strong>Status:</strong> <input type="text" name="Status" value="<?php echo $Status; ?>"/><br/><br>
<strong>Comments:</strong> <input type="text" name="Comments" value="<?php echo $Comments; ?>"/><br/><br>
<strong>Type:</strong> <input type="text" name="Type" value="<?php echo $Type; ?>"/><br/><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$Name = mysql_real_escape_string(htmlspecialchars($_POST['Name']));
$Status = mysql_real_escape_string(htmlspecialchars($_POST['Status']));
$Comments = mysql_real_escape_string(htmlspecialchars($_POST['Comments']));
$Type = mysql_real_escape_string(htmlspecialchars($_POST['Type']));
// check that firstname/lastname fields are both filled in
if ($Name == '' || $Type == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $Name, $Status, $Comments, $Type, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE Schools SET Name='$Name', Status='$Status', Comments='$Comments', Type='$Type' WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM Schools WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$Name = $row['Name'];
$Status = $row['Status'];
$Comments = $row['Comments'];
$Type = $row['Type'];
// show form
renderForm($id, $Name, $Status, $Comments, $Type, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
I am wanting to replace the status text filed with a drop down list of options.
Replace your <input by <select :
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>School Name:</strong> <input type="text" name="Name" value="<?php echo $Name; ?>"/><br/><br>
<!-- <strong>Status:</strong> <input type="text" name="Status" value="<?php echo $Status; ?>"/><br/><br>-->
<strong>Status:</strong> <select name="Status">
<option value="1">Status 1</option>
<option value="2">Status 2</option>
</select>
<strong>Comments:</strong> <input type="text" name="Comments" value="<?php echo $Comments; ?>"/><br/><br>
<strong>Type:</strong> <input type="text" name="Type" value="<?php echo $Type; ?>"/><br/><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
If your statuses are in a table, fill the <select> with a query :
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>School Name:</strong> <input type="text" name="Name" value="<?php echo $Name; ?>"/><br/><br>
<!-- <strong>Status:</strong> <input type="text" name="Status" value="<?php echo $Status; ?>"/><br/><br>-->
<strong>Status:</strong> <select name="Status">
<?php
$result = mysql_query("SELECT * FROM tbl_status",$cnx);
while ( $row = mysql_fetch_array($result) )
echo "<option value='" . $row["id"] . "'>" . $row["text"] . "</option>";
?>
</select>
<strong>Comments:</strong> <input type="text" name="Comments" value="<?php echo $Comments; ?>"/><br/><br>
<strong>Type:</strong> <input type="text" name="Type" value="<?php echo $Type; ?>"/><br/><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
You could use the html <datalist> or the <select> tag.
I hope I could help.
First of all you need to switch from mysql_* to mysqli_* as it going to get removed in php 7.0 I'm using this function i created and it might help you
here is the php code
function GetOptions($request)
{
global $con;
$sql = "SELECT * FROM data GROUP BY $request ORDER BY $request";
$sql_result = mysqli_query($con, $sql) or die('request "Could not execute SQL query" ' . $sql);
while ($row = mysqli_fetch_assoc($sql_result)) {
echo "<option value='" . $row["$request"] . "'" . ($row["$request"] == $_REQUEST["$request"] ? " selected" : "") . ">" . $row["$request"] . "$x</option>";
}
}
and the html code goes like
<label>genre</label>
<select name="genre">
<option value="all">all</option>
<?php
GetOptions("genre");
?>
</select>
I am trying to insert 4 forms that are the same. but with different values to mysql using PHP.
When I submit my data, the database only takes the values from the last form and inserts it 4 times. I am trying to get the values from all 4 on submit.
<div class="req3">
<h1>Requirement 4</h1>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<br>
Enter info for 4 teams and it will inserted into the database<br><br>
<div class="sqlForm">
<p class="formHead">Team 1</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br>
</div>
<div class="sqlForm">
<p class="formHead">Team 2</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br>
</div>
<div class="sqlForm">
<p class="formHead">Team 3</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br>
</div>
<div class="sqlForm">
<p class="formHead">Team 4</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br><br></div>
<input class="styled-button" type="submit" name="insert" value="Submit">
</form>
<?php
if (isset($_POST['insert'])) {
insertTable();
} else {
$conn->close();
}
function insertTable() {
$servername = "localhost:3306";
$username = "XXXXX";
$password = "XXXXX";
$dbname = "XXXXX";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
echo ("Connection failed: " . $conn->connect_error);
} else {
$varTname = $_POST['teamname'];
$varCity = $_POST['city'];
$varBplayer = $_POST['bestplayer'];
$varYearformed = $_POST['yearformed'];
$varWebsite = $_POST['website'];
$sql = "INSERT INTO Teams (teamname, city, bestplayer, yearformed, website)
VALUES ('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite')";
if ($conn->multi_query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysql_query($sql);
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
}
}
?>
chnage the names of your controls so they Post as Arrays
<input type="text" name="teamname[G1]">
<input type="text" name="teamname[G2]">
this why when you use $varTname = $_POST['teamname']; $varTname is an array and each of the 4 values of teamname are set as $varTname['G#'] where # matches the number you set for that group of input fields.
then use a for loop to get the data and execute your query, something like bellow. while you at it you can also fix up your SQL Injection vulnerability. you may also want to so some more sanitation to the data just to be sure
$varTname = $_POST['teamname'];
$varCity = $_POST['city'];
$varBplayer = $_POST['bestplayer'];
$varYearformed = $_POST['yearformed'];
$varWebsite = $_POST['website'];
$stmt = $mysqli->prepare('INSERT INTO Teams (teamname, city, bestplayer, yearformed, website) VALUES (?,?,?,?,?,?)');
$varTname1Bind = "";
$varTnameBind = "";
$varCityBind = "";
$varBplayerBind = "";
$varWebsiteBind = "";
// assuming they are all strings, adjust where needed
$stmt->bind_param('sssssss',
$varTname1Bind,
$varTnameBind,
$varCityBind,
$varBplayerBind,
$varYearformedBind,
$varWebsiteBind);
for($i = 1; i < 5; $i++)
{
$varTname1Bind = $varTname['G'.$i];
$varTnameBind = $varTname['G'.$i];
$varCityBind = $varCity['G'.$i];
$varBplayerBind = $varBplayer['G'.$i];
$varYearformedBind = $varYearformed['G'.$i];
$varWebsiteBind = $varWebsite['G'.$i];
$stmt->execute();
}
will save you on how much code you need to do
You can convert your input names into arrays by adding [] then in your php loop through the array of the $_POST[] and built up your $sql by concatenating the values until you finish looping through all values and INSERT it as multiple values.
HTML:
<label>Team Name:</label> <input type="text" name="teamname[]"><br>
<label>City:</label> <input type="text" name="city[]"><br>
<label>Best Player:</label> <input type="text" name="bestplayer[]"><br>
<label>Year Formed:</label> <input type="text" name="yearformed[]"><br>
<label>Website:</label> <input type="text" name="website[]"><br>
PHP:
<?php
$sql = "INSERT INTO Teams (teamname, city, bestplayer, yearformed, website) VALUES ";
for($i = 0 ; $i < count($_POST['teamname']) ; $i++){
$varTname = $_POST['teamname'][$i];
$varCity = $_POST['city'][$i];
$varBplayer = $_POST['bestplayer'][$i];
$varYearformed = $_POST['yearformed'][$i];
$varWebsite = $_POST['website'][$i];
$sql .= "(" .$varTname. " , " .$varCity. " , " .$varBplayer. " , " .$varYearformed. " , " .$varWebsite. "),";
}
$sql = rtrim($sql, ','); // omit the last comma
// Then Excute your query
?>
This way you don't need to give them unique names name="test1", name="test2" and so, to see it in action check this PHP Fiddle in the bottom of the result page, I've already set the values of the input fields, just hit submit and go to the bottom of the result page to see the composed INSERT statement.
NOTE that the above SQL is just a demo on how to build it up, DO NOT use it like this without validation and sanitizing.. ALSO STOP querying this way and instead use Prepared Statements with PDO or MySQLi to avoid SQL Injection.
So for MySQLi prepared statements, procedural style - I work with PDO - as you see in this PHP Fiddle 2, the code is:
<?php
// you validation goes here
if (isset($_POST['insert'])) {
insertTable();
} else {
$conn->close();
}
function insertTable() {
// enter your credentials below and uncomment it to connect
//$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
$sql = "INSERT INTO Teams (teamname, city, bestplayer, yearformed, website) VALUES";
$s = '';
$bind = '';
for($i = 0 ; $i < count($_POST['teamname']) ; $i++){
$sql .= " (?, ?, ?, ?, ?)";
$s .= 's';
$varTname = $_POST['teamname'][$i];
$varCity = $_POST['city'][$i];
$varBplayer = $_POST['bestplayer'][$i];
$varYearformed = $_POST['yearformed'][$i];
$varWebsite = $_POST['website'][$i];
$bind .= " , " . $varTname. " , " .$varCity. " , " .$varBplayer. " , " .$varYearformed. " , " .$varWebsite;
}
$sql = rtrim($sql, ','); // omit the last comma
$s = "'" .$s. "'";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, $s , $bind);
mysqli_stmt_execute($stmt);
}
?>
Normally this is done by creating arrays of form controller.
<input type="text" name="teamname[]">
<input type="text" name="city[]">
And then you can get an array in post request.
Hope this helps!
use different name like teamname1,teamname2,teamname3,teamname4
<input type="text" name="teamname1">
<input type="text" name="teamname2">
<input type="text" name="teamname3">
<input type="text" name="teamname4">
For get values :-
$varTname1 = $_POST['teamname1'];
$varTname2 = $_POST['teamname2'];
$varTname3 = $_POST['teamname3'];
$varTname4 = $_POST['teamname4'];
For insert values :-.
$sql = "INSERT INTO Teams (teamname)
VALUES ('$varTname1'),
('$varTname2'),
('$varTname3'),
('$varTname4')
or you can try this:-
<input type="text" name="teamname[]">
Get value like :-
$_POST['teamname'][0]
try this method
$sql = "INSERT INTO Teams (teamname, city, bestplayer,yearformed,website)
VALUES ('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
";
$sql.= query same as abov
$sql.= query same as abov
$sql.= query same as abov
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
note the . dot after the first query.
I think you should also use an auto increment keyThis should work.
I have built a database named "artStore" and a table within that database named "inventory". I've been able to figure out how to create a new entry to the database, but I'm trying to create a page that can edit those entries.
Here is "inventory" the table I created:
$sql = "CREATE TABLE inventory (
id INT(6) AUTO_INCREMENT PRIMARY KEY,
product VARCHAR(30),
category VARCHAR(30),
seller VARCHAR(30)
)";
Here is what I'm currently trying:
<?php
$resultProduct = "product";
$resultCategory = "category";
$resultSeller = "seller";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultProduct = $row["product"];
$resultCategory = $row["category"];
$resultSeller = $row["seller"];
}
} else {
echo "No Results";
}
?>
<form action="update.php" method="POST">
<label for="product">Product</label>
<input id="product" type="text" name="product" value="<?php echo $resultProduct; ?>">
<br>
<label for="category">Category:</label>
<input id="category" type="text" name="category" value="<?php echo $resultCategory; ?>">
<br>
<label for="seller">Seller:</label>
<input id="seller" type="text" name="seller" value="<?php echo $resultSeller; ?>">
<br>
<input id="id" type="text" name="id" value="<?php echo $resultId; ?>" style="display:none;">
<input type="submit" value="Update My Record">
</form>
What I'm trying in update.php
$product = $_POST['product'];
$category = $_POST['category'];
$seller = $_POST['seller'];
$sql = "INSERT INTO inventory (product, category, seller) VALUES ('$product', '$category', '$seller')";
if ($connection->query($sql) === true) {
echo "Inserted Successfully";
} else {
echo "Error occured in the insert: " . $connection->error;
}
$connection->close();
Try the below code I added hidden field on form and changes on your sql query
<?php
$resultProduct = "product";
$resultCategory = "category";
$resultSeller = "seller";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultProduct = $row["product"];
$resultCategory = $row["category"];
$resultSeller = $row["seller"];
$resultId = $row["id"];
}
} else {
echo "No Results";
}
?>
<form action="update.php" method="POST">
<input type="text" name="update_id" value="<?php echo $resultId; ?>">
<label for="product">Product</label>
<input id="product" type="text" name="product" value="<?php echo $resultProduct; ?>">
<br>
<label for="category">Category:</label>
<input id="category" type="text" name="category" value="<?php echo $resultCategory; ?>">
<br>
<label for="seller">Seller:</label>
<input id="seller" type="text" name="seller" value="<?php echo $resultSeller; ?>">
<br>
<input id="id" type="text" name="id" value="<?php echo $resultId; ?>" style="display:none;">
<input type="submit" value="Update My Record">
</form>
In update.php
$product = $_POST['product'];
$category = $_POST['category'];
$seller = $_POST['seller'];
$updateId = $_POST['update_id'];
$sql = "UPDATE inventory set product = '$product',category='$category',seller='$seller' WHERE id = '$updateId'";
<?php
$resultProduct = "product";
$resultCategory = "category";
$resultSeller = "seller";
$resultId = "product_id";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultProduct = $row["product"];
$resultCategory = $row["category"];
$resultSeller = $row["seller"];
$resultid = $row["id"];
}
} else {
echo "No Results";
}
?>
You were using $resultId in the form but you have not declared and assigned a value to it in the loop.
<form action="update.php" method="POST">
<input id="id" type="hidden" name="id" value="<?php echo $resultId; ?>">
<label for="product">Product</label>
<input id="product" type="text" name="product" value="<?php echo $resultProduct; ?>">
<br>
<label for="category">Category:</label>
<input id="category" type="text" name="category" value="<?php echo $resultCategory; ?>">
<br>
<label for="seller">Seller:</label>
<input id="seller" type="text" name="seller" value="<?php echo $resultSeller; ?>">
<br>
<input type="submit" value="Update My Record">
</form>
<!-- Instead of passing the ID in textbox with display: none you can pass it directly in hidden -->
<?php
$product = $_POST['product'];
$category = $_POST['category'];
$seller = $_POST['seller'];
$product_id = $_POST['id'];
if($product_id!='')//MEANS WE HAVE TO UPDATE THE RECORD
{
// UPDATE QUERY WILL UPDATE THE SAME RECORD ONLY MATCHING THE UNIQUE PRODUCT ID
$sql = "UPDATE inventory SET product = '$product', category = '$category', seller = '$seller' WHERE id = '$product_id' LIMIT 1";
if ($connection->query($sql) === true) {
echo "Updated Successfully";
} else {
echo "Error occured in the insert: " . $connection->error;
}
}
else// If id is blank it means you have a new record
{
$sql = "INSERT INTO inventory (product, category, seller) VALUES ('$product', '$category', '$seller')";
if ($connection->query($sql) === true) {
echo "Inserted Successfully";
} else {
echo "Error occured in the insert: " . $connection->error;
}
}
$connection->close();
?>