Posting info from PHP to a database [duplicate] - php

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();
?>

Related

HTML Form: Select-Option to insert data into MySQL phpmyadmin database

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'];

Update value based on checkbox selected

I am trying to update the value in a text box based on selections made on the form. When a user checks a box for an option, I am trying to get the total cost to increase by a defined amount. Everything else is working on the form and if I change the cost value manually it will post to database correctly. Is this possible with my approach or do I need to resort to a different technique?
<HEAD>
<script>
function tally()
{
Cost = 60;
if (Document.edituser.survivor10.checked ) { Cost = Cost + 10; }
if (document.edituser.high5.checked ) { Cost = Cost + 10; }
if (document.edituser.margin.checked == true ) { Cost = Cost + 10; }
if (document.edituser.survivor20.checked == true ) { Cost = Cost + 20; }
if (document.edituser.confidence.checked == true ) { Cost = Cost + 10; }
if (document.edituser.loser.checked == true ) { Cost = Cost + 10; }
if (document.edituser.vegas.checked == true ) { Cost = Cost + 10; }
document.edituser.cost.value = Cost;
}
<?php
require('includes/application_top.php');
include('includes/classes/class.formvalidation.php');
if (isset($_POST['submit'])) {
$my_form = new validator;
if($my_form->checkEmail($_POST['email'])) { // check for good mail
if ($my_form->validate_fields('firstname,lastname,email,password')) { //
comma delimited list of the required form fields
if ($_POST['password'] == $_POST['password2']) {
$salt = substr($crypto->encrypt((uniqid(mt_rand(), true))), 0, 10);
$secure_password = $crypto->encrypt($salt . $crypto->encrypt($_POST['password']));
$sql = "update nflp_users ";
$sql .= "set password = '".$secure_password."', salt = '".$salt."', firstname = '".$_POST['firstname']."', lastname = '".$_POST['lastname']."', textOption = '".$_POST['textOption']."', phone = '".$_POST['phone']."', carrier = '".$_POST['carrier']."', email = '".$_POST['email']."', survivor10 = '".$_POST['survivor10']."', survivor20 = '".$_POST['survivor20']."', loser = '".$_POST['loser']."', margin = '".$_POST['margin']."', high5 = '".$_POST['high5']."', vegas = '".$_POST['vegas']."', confidence = '".$_POST['confidence']."', cost = '".$_POST['cost']."'";
$sql .= "where userID = " . $user->userID . ";";
//die($sql);
$mysqli->query($sql) or die($mysqli->error);
//set confirmation message
$display = '<div class="responseOk">Account updated successfully.</div><br/>';
} else {
$display = '<div class="responseError">Passwords do not match, please try again.</div><br/>';
}
} else {
$display = str_replace($_SESSION['email_field_name'], 'Email', $my_form->error);
$display = '<div class="responseError">' . $display . '</div><br/>';
}
} else {
$display = '<div class="responseError">There seems to be a problem with your email address, please check.</div><br/>';
}
}
include('includes/header.php');
$sql = "select * from " . DB_PREFIX . "users where userID = " . $user->userID;
$query = $mysqli->query($sql);
if ($query->num_rows > 0) {
$row = $query->fetch_assoc();
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$email = $row['email'];
$survivor10 = $row['survivor10'];
$survivor20 = $row['survivor20'];
$loser = $row['loser'];
$margin = $row['margin'];
$high5 = $row['high5'];
$confidence = $row['confidence'];
$vegas = $row['vegas'];
// $textOption = $row['textOption'];
// $phone = $row['phone'];
// $carrier = $row['carrier'];
$cost = $row['cost'];
}
if (!empty($_POST['firstname'])) $firstname = $_POST['firstname'];
if (!empty($_POST['lastname'])) $lastname = $_POST['lastname'];
if (!empty($_POST['email'])) $email = $_POST['email'];
if (!empty($_POST['survivor10'])) $survivor10 = $_POST['survivor10'];
if (!empty($_POST['survivor20'])) $survivor20 = $_POST['survivor20'];
if (!empty($_POST['loser'])) $loser = $_POST['loser'];
if (!empty($_POST['margin'])) $margin = $_POST['margin'];
if (!empty($_POST['high5'])) $high5 = $_POST['high5'];
if (!empty($_POST['confidence'])) $confidence = $_POST['confidence'];
if (!empty($_POST['vegas'])) $vegas = $_POST['vegas'];
// if (!empty($_POST['textOption'])) $textOption = $_POST['textOption'];
// if (!empty($_POST['phone'])) $phone = $_POST['phone'];
// if (!empty($_POST['carrier'])) $carrier = $_POST['carrier'];
if (!empty($_POST['cost'])) $cost = $_POST['cost'];
?>
<h1>Edit User Account Details</h1>
<?php if(isset($display)) echo $display; ?>
<form action="user_edit.php" method="post" name="edituser">
<fieldset>
<legend style="font-weight:bold;">Enter User Details:</legend>
<p>First Name:<br />
<input type="text" name="firstname" value="<?php echo $firstname; ?>"></p>
<p>Last Name:<br />
<input type="text" name="lastname" value="<?php echo $lastname; ?>"></p>
<p>Email:<br />
<input type="text" name="email" value="<?php echo $email; ?>" size="30"></p>
<p>New Password:<br />
<input type="password" name="password" value=""></p>
<p>Confirm Password:<br />
<input type="password" name="password2" value=""></p><br>
<tr><td></td></tr>
<legend style="font-weight:bold;">Side Pools:</legend>
<tr>
<p><type=hidden value=" " name="survivor10" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="survivor10" <? if($survivor10== "1") {echo "checked";} ?>><b> Survivor $10</b></p>
<p><type=hidden value=" " name="survivor20" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="survivor20" <? if($survivor20== "1") {echo "checked";} ?>><b> Survivor2 $20</b></p>
<p><type=hidden value=" " name="loser" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="loser" <? if($loser== "1") {echo "checked";} ?> ><b> Loser $10</b></p>
<p><type=hidden value=" " name="high5" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="high5" <? if($high5== "1") {echo "checked";} ?>><b> High 5 $10</b></p>
<p><type=hidden value=" " name="margin" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="margin" <? if($margin== "1") {echo "checked";} ?> ><b> Margin $10</b></p>
<p><type=hidden value=" " name="vegas" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="vegas" <? if($vegas== "1") {echo "checked";} ?> ><b> Vegas $10</b></p>
<p><type=hidden value=" " name="confidence" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="confidence" <? if($confidence== "1") {echo "checked";} ?>><b> Confidence $10</b></p>
</tr><br>
<td><font color=red>Your Total Fee Is :</font><input type="int" size="3" name="cost" value= "<? if($cost!= "") {echo "$cost"; } else {echo "60";}?>"</td><br><br>
<!--<tr>Text alert option: Message and data rates may apply. Expect approx. 3 msgs/week.</tr> -->
<p><input type="submit" name="submit" value="Submit" class="btn btn-primary"></p>
</fieldset>
</form>
JavaScript is case sensitive, so Document and document are two different things. In your case, you want to use document. So you should change all if conditions inside tally, to use document.
Btw. never trust the user! You could do the calculation on the client side as an indicator for the user, but you should definitly do it again on the serverside or everyone could post costs as the like - even negative ones.

Trying to update mysql database form in php

My database manages to retrieve values when I navigate from the previous page.
When I click the 'Update Product' button, the line Update product appears. What I want is when I click the 'Update Product' button, and have modified a record beforehand, I would hope to update the database with the values as well and a confirmation message is displayed to confirm this.
Code:
<form id="updateForm" name="updateForm" action="<?php echo "?mode=update&ID=" . $productDetails["ID"]; ?>" method="post">
<div>
<label for="updateFormProductCostPrice">ID</label>
<input id="updateFormProductCostPrice" name="ID" type="text" readonly
value="<?php echo $productDetails["ID"]; ?>">
</div>
<div>
<label for="updateFormProductName">Film Name</label>
<input id="updateFormProductName" name="FilmName" type="text"
value="<?php echo $productDetails["FilmName"]; ?>">
</div>
<div>
<label for="updateFormProductDescription">Producer</label>
<input id="Producer" name="productDescription" type="text"
value="<?php echo $productDetails["Producer"]; ?>">
</div>
<div>
<label for="updateFormProductPrice">Year Published</label>
<input id="updateFormProductPrice" name="YearPublished" type="text"
value="<?php echo $productDetails["YearPublished"]; ?>">
</div>
<div>
<label for="updateFormProductStock">Stock:</label>
<input id="updateFormProductStock" name="Stock" type="text"
value="<?php echo $productDetails["Stock"]; ?>">
</div>
<div>
<label for="updateFormProductEan">Price:(&#163)</label>
<input id="updateFormProductEan" name="Price" type="text"
value="<?php echo $productDetails["Price"]; ?>">
</div>
<div>
<input id="updateSubmit" name="updateSubmit" value="Update product" type="submit">
</div>
</form>
PHP:
if (((!empty($_GET["mode"])) && (!empty($_GET["ID"]))) && ($_GET["mode"] == "update")) {
echo "<h1>Update product</h1>";
if (isset($_POST["updateSubmit"])) {
if ((!empty($_POST["ID"])) && (!empty($_POST["FilmName"]))
&& (!empty($_POST["Producer"])) && (!empty($_POST["YearPublished"]))
&& (!empty($_POST["Stock"])) && (!empty($_POST["Price"]))) {
$query = "UPDATE ProductManagement "
. "SET FilmName = '" . $_POST["FilmName"] . "', "
. "Producer = '" . $_POST["Producer"] . "', "
. "YearPublished = '" . $_POST["YearPublished"] . "', "
. "Stock = " . $_POST["Stock"] . ", "
. "Price = '" . $_POST["Price"] . "' "
. "WHERE ID=" . $_GET['ID'] . ";";
$result = mysqli_query($connection, $query);
if ($result == false) {
echo "<p>Updating failed.</p>";
} else{
echo "<p>Updated</p>";
}
}
}
}
So I need the database to update what new value I have entered and it once the 'Update product' Button is pressed, the original value appears and the value is not updated on the database. Why is this? I don't get any error messages. Thanks
The error is that you dont POST the ID but you GET the ID value. input boxes with the readonly attribute don't post values.
change:
if ((!empty($_POST["ID"])) && (!empty($_POST["FilmName"]))
to:
if ((!empty($_GET["ID"])) && (!empty($_POST["FilmName"]))
Edit: Total changes to make to make this work:
HTML:
<form id="updateForm" name="updateForm" action="<?php echo "?mode=update&ID=" . $productDetails["ID"]; ?>" method="post">
<div>
<label for="updateFormProductID">ID</label>
<input id="updateFormProductID" name="ID" type="text" readonly
value="<?php echo $productDetails["ID"]; ?>">
</div>
<div>
<label for="updateFormProductName">Film Name</label>
<input id="updateFormProductName" name="FilmName" type="text"
value="<?php echo $productDetails["FilmName"]; ?>">
</div>
<div>
<label for="updateFormProductProducer">Producer</label>
<input id="updateFormProductProducer" name="Producer" type="text"
value="<?php echo $productDetails["Producer"]; ?>">
</div>
<div>
<label for="updateFormProductYearPublished">Year Published</label>
<input id="updateFormProductYearPublished" name="YearPublished" type="text"
value="<?php echo $productDetails["YearPublished"]; ?>">
</div>
<div>
<label for="updateFormProductStock">Stock:</label>
<input id="updateFormProductStock" name="Stock" type="text"
value="<?php echo $productDetails["Stock"]; ?>">
</div>
<div>
<label for="updateFormProductPrice">Price:(&#163)</label>
<input id="updateFormProductPrice" name="Price" type="text"
value="<?php echo $productDetails["Price"]; ?>">
</div>
<div>
<input id="updateSubmit" name="updateSubmit" value="Update product" type="submit">
</div>
</form>
PHP:
if (((!empty($_GET["mode"])) && (!empty($_GET["ID"]))) && ($_GET["mode"] == "update")) {
echo "<h1>Update product</h1>";
if (isset($_POST["updateSubmit"])) {
if ((!empty($_GET["ID"])) && (!empty($_POST["FilmName"]))
&& (!empty($_POST["Producer"])) && (!empty($_POST["YearPublished"]))
&& (!empty($_POST["Stock"])) && (!empty($_POST["Price"]))) {
$query = "UPDATE ProductManagement "
. "SET FilmName = '" . $_POST["FilmName"] . "', "
. "Producer = '" . $_POST["Producer"] . "', "
. "YearPublished = '" . $_POST["YearPublished"] . "', "
. "Stock = " . $_POST["Stock"] . ", "
. "Price = '" . $_POST["Price"] . "' "
. "WHERE ID=" . $_GET['ID'] . ";";
$result = mysqli_query($connection, $query);
if ($result == false) {
echo "<p>Updating failed.</p>";
} else{
echo "<p>Updated</p>";
}
}
}
}
Try setting the name and id of your input fields to the same respective values. I see you call id from one and name from another input field in your php and it might be causing the function to fail.
Like so for example:
<label for="ID">ID</label>
<input id="ID" name="ID" type="text" readonly value="<?php echo $productDetails["ID"]; ?>">
you should be fine using $_POST[], since the method of your form is POST. (If you change it to GET it will put all the values in the url)

Using PHP “insert multiple” to insert all 4 rows at the same time

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.

how to update postgresql rows using php?

first I want to say that I'm a beginner in postgresql and php.. my company told me to create a database that they can view and edit on local server.. so I created the database in postgresql.. created a page that views the database:
<html>
<head>
<title>Ongoing projects</title>
</head>
<body bgcolor="666657">
<?php
//database access information
require_once("DB.php");
$host = "localhost";
$user = "admin";
$pass = "";
$db = "Project_list";
$port = "5432";
//open a connection to the database server
$connection = pg_connect("host=$host dbname=$db user=$user password=$pass port=$port");
if (!$connection)
{
die("Could not open connection to database server");
}
?>
<?php
$query = 'select * from ongoing';
$result = pg_query($query); $i = 0;
echo '<html><table bgcolor="666657" width="10" height="30" border="0" cellpadding="0" cellspacing="0"><td align="center"> <h1><font color = "#ffb200"> Ongoing projects</h1>';
echo '<html><body><table border= 2 BORDERCOLOR="000000" cellpadding="1" cellspacing="0"> <tr >';
while ($i < pg_num_fields($result)) {
$fieldName =pg_field_name($result, $i);
echo '<b>'.'<td width="2" bgcolor="666657" align="center">'.'<font color = "#ffb200">'. '</b>'.'<b>'. $fieldName . '</b>'. '</td>';
$i = $i + 1; }
echo("<td><align= center><font color = #ffb200><b>Action</td>");
echo '</tr>' ;
$i = 0;
while ($row = pg_fetch_row($result)) {
echo '<tr align="center" width="1">';
$count = count($row);
$y = 0;
while ($y < $count) {
$c_row = current($row);
echo '<td>' .'<font color = "#ffb200">'. $c_row . '</td>';
next($row);
$y = $y + 1;
}
echo("<td><align= center><a href='editongoing.php?ProjectID=".$row[0]."'>Edit</a></td>");
echo '</tr>';
$i = $i + 1;
}
pg_free_result($result);
echo '</table></body></html>';
?>
<h3>
<a href="projects.php"</a>Back to projects page</a>
</h3>
<SCRIPT LANGUAGE="JavaScript">
if (window.print) {
document.write('<form> '
+ '<input type=button name=print value="Click" '
+ 'onClick="javascript:window.print()"> To Print!</form>');
}
// End -->
</script>
when you click the edit button, you will go to this page where you can edit the raw you want, this is the (edit) code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Edit Ongoing projects</title>
</head>
<body bgcolor="666657">
<?php
// attempt a connection
$connection = pg_connect("host=localhost dbname=Project_list user=admin password=");
if (!$connection) {
die("Error in connection: " . pg_last_error());
}
if ($_REQUEST['ProjectID']!=''){
$QueryStr = "Select * from ongoing where project_no='".$_REQUEST['ProjectID']."'";
$result = pg_query($connection, $QueryStr);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
$row = pg_fetch_row($result);
print_r($row);
}
if ($_POST['submit']) {
// escape strings in input data
$project_no = pg_escape_string($_POST['project_no']);
$title = pg_escape_string($_POST['title']);
$duration = pg_escape_string($_POST['duration']);
$manager = pg_escape_string($_POST['manager']);
$country = pg_escape_string($_POST['country']);
$total_fee = pg_escape_string($_POST['totalfee']);
$performed = pg_escape_string($_POST['performed']);
$remaining = pg_escape_string($_POST['remaining']);
$gross_profit = pg_escape_string($_POST['gross_profit']);
$gp = pg_escape_string($_POST['gp']);
$performance_year = pg_escape_string($_POST['performance_year']);
$gp_year = pg_escape_string($_POST['gp_year']);
// execute query
$sql = "INSERT INTO ongoing (project_no, project_title, duration, manager, country, total_fee,
performed, remaining, gross_profit, gp, performance_year, gp_year)
VALUES('$project_no', '$title', '$duration', '$manager', '$country','$total_fee','$performed','$remaining',
'$gross_profit','$gp', '$performance_year','$gp_year')";
$result = pg_query($connection, $sql);
f (!$result) {
die("Error in SQL query: " . pg_last_error());
}
echo "Data successfully inserted!";
// free memory
pg_free_result($result);
// close connection
pg_close($connection);
}
?>
<form action= "<?php echo $_SERVER['PHP_SELF']; ?>" method="post"><b><font color = "#ffb200">
Project No.: <br> <input id="project_no" type="text" name="project_no" size="20" value=<?= $row[0] ?>>
<p>
Project Title: <br> <input id="title" type="text" name="title" value='<?= $row[1] ?>'>
<p>
Duration: <br> <input ID="duration" type="text" name="duration" value=<?= $row[2] ?>>
<p>
Project Manager: <br> <input ID="manager" type="text" name="manager" value=<?= $row[3] ?>>
<p>
Country: <br> <input ID="country" type="text" name="country" value=<?= $row[4] ?>>
<p>
Total Fee: <br> <input ID="totalfee" type="text" name="total_fee" value=<?= $row[5] ?>>
<p>
Already performed: <br> <input ID="performed" type="text" name="performed" value=<?= $row[6] ?>>
<p>
Remaining performance: <br> <input ID="remaining" type="text" name="remaining" value=<?= $row[7] ?>>
<p>
Gross Profit: <br> <input ID="gross_profit" type="text" name="gross_profit" value='<?= $row[8] ?>'>
<p>
GP%: <br> <input ID="gp" type="text" name="gp" value=<?= $row[9] ?>>
<p>
Performance actual year: <br> <input ID="performance_year" type="text" name="performance_year" value=<?= $row[10] ?>>
<p>
GP actual year: <br> <input ID="gp_year" type="text" name="gp_year" value=<?= $row[11] ?>>
<p>
<input type="submit" name="submit" value="Sumbit my table" size="30">
<P>
<a href="ongoing.php"</a>View ongoing projects</a>
<a href="editproject.php"</a>Back to editing menu</a>
</form>
</body>
</html>
My problem is, when I edit the data and click on submit my table, a new raw is inserted.. but I want it to be updated not inserted... help plz
You need to select which record (id number) you want to update, and then your query will look like
$sql = "UPDATE ongoing SET field1='value', field2='value' ... WHERE id = 'id of project you want to edit'";

Categories