PHP MySQL row editor showing in wrong order - php

Trying to make something so I can edit rows from database using a PHP form but when I click edit it shows in the wrong order.
I know I can't edit the top one because it's ID is 0 and i'll change that later on but the others are showing when editing they are Text, Name, Rank
But I want them to be Name, Rank, Text
You can try for yourself here:http://rumblegaming.co.uk/admin/home
<?php
/*
Allows the user to both create new records and edit existing records
*/
// connect to the database
include("connect.php");
// creates the new/edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($name = '', $rank ='', $text ='', $error = '', $id = '')
{ ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
<?php if ($id != '') { echo "Edit Record"; } else { echo "New Record"; } ?>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1><?php if ($id != '') { echo "Edit Record"; } else { echo "New Record"; } ?></h1>
<?php if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
. "</div>";
} ?>
<form action="" method="post">
<div>
<?php if ($id != '') { ?>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<p>ID: <?php echo $id; ?></p>
<?php } ?>
<strong>Name:</strong> <input type="text" name="name"
value="<?php echo $name; ?>"/><br/>
<strong>Rank:</strong> <input type="text" name="rank"
value="<?php echo $rank; ?>"/><br/>
<strong>Text:</strong> <input type="text" name="text"
value="<?php echo $text; ?>"/><br/>
<input type="submit" name="submit" value="Submit" />
</div>
</form>
</body>
</html>
<?php }
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['id']))
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id']))
{
// get variables from the URL/form
$id = $_POST['id'];
$name = htmlentities($_POST['name'], ENT_QUOTES);
$rank = htmlentities($_POST['rank'], ENT_QUOTES);
$text = htmlentities($_POST['text'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($name == '' || $rank == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($name, $rank, $text, $error, $id);
}
else
{
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE Team SET name = ?, rank = ?, text = ? WHERE id=?"))
{
$stmt->bind_param("sssi", $name, $rank, $text, $id);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: home");
}
}
// if the 'id' variable is not valid, show an error message
else
{
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else
{
// make sure the 'id' value is valid
if (is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// get 'id' from URL
$id = $_GET['id'];
// get the recod from the database
if($stmt = $mysqli->prepare("SELECT * FROM Team WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $rank, $text, $name);
$stmt->fetch();
// show the form
renderForm($name, $rank, $text, NULL, $id);
$stmt->close();
}
// show an error if the query has an error
else
{
echo "Error: could not prepare SQL statement";
}
}
// if the 'id' value is not valid, redirect the user back to the view.php page
else
{
header("Location: home");
}
}
}
/*
NEW RECORD
*/
// if the 'id' variable is not set in the URL, we must be creating a new record
else
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// get the form data
$firstname = htmlentities($_POST['firstname'], ENT_QUOTES);
$lastname = htmlentities($_POST['lastname'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($firstname == '' || $lastname == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($firstname, $lastname, $error);
}
else
{
// insert the new record into the database
if ($stmt = $mysqli->prepare("INSERT players (firstname, lastname) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $firstname, $lastname);
$stmt->execute();
$stmt->close();
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare SQL statement.";
}
// redirec the user
header("Location: view.php");
}
}
// if the form hasn't been submitted yet, show the form
else
{
renderForm();
}
}
// close the mysqli connection
$mysqli->close();
?>

You can simply re-arrange your select statement.
eg. instead of
if($stmt = $mysqli->prepare("SELECT * FROM Team WHERE id=?"));
use
if($stmt = $mysqli->prepare("SELECT Name, Rank, Text FROM Team WHERE id=?"));

Related

Insert Foreign Key value from PHP using SELECT option

I creating an inventory web-base system by using php and php myadmin (InnoDB). I want to insert the value in inventory when I inserting the record, I can see the data of the (FK) in the dropdown but when I submit the form the data to the db, it returns as no input value in the field and the dropdown not there anymore. Is the way I'm using the foreign key in the dropdown wrong?
I have a table that contains multiple foreign keys.
Table Inventory(
id (pk),
name,
condition_(fk),
producttype (fk))
Table condition_type(
condition_ (pk))
Table producttype(
producttype(fk))
<?php
// Include config file
require_once "../config.php";
// Define variables and initialize with empty values
$name = $condition_ = $producttype = "";
$name_err = $condition_err = $producttype_err = "";
$sql2 = "SELECT * FROM condition_type";
$sql4 = "SELECT * FROM producttype";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate name
$input_name = trim($_POST["name"]);
if(empty($input_name)){
$name_err = "Please enter a name.";
}else{
$name = $input_name;
}
// Validate condition
$input_condition = trim($_POST["condition_"]);
if(empty($input_condition)){
$condition_err = "Please choose the condition.";
} else{
$condition_ = $input_condition;
}
// Validate producttype
$input_producttype = trim($_POST["prodcuttype"]);
if(empty($input_producttype)){
$producttype_err = "Please enter the product type..";
} else{
$producttype = $input_producttype;
}
// Check input errors before inserting in database
if(empty($name_err) && empty($condition_err) && empty($producttype_err)){
// Prepare an insert statement
$sql = "INSERT INTO inventory (name, condition_, producttype) VALUES (?, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("sss", $param_name, $param_condition, $param_producttype);
// Set parameters
$param_name = $name;
$param_condition = $condition;
$param_producttype = $producttype;
// Attempt to execute the prepared statement
if($stmt->execute()){
// Records created successfully. Redirect to landing page
header("location: ../application");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
// Close connection
$mysqli->close();
}
?>
-------> This is the form
<div class="form-group <?php echo (!empty($condition_err)) ? 'has-error'
: ''; ?>">
<label>Condition</label>
</br>
<select id="condition_" name="condition_" class="form-control" value="<?
php echo $condition_ ;?>">
<option>Please Select Product Condition</option>
<?php
if($result2 = $mysqli ->query($sql2)){
while($row = $result2->fetch_array()){
echo "<option value=".$row['condition_'].">" .$row['condition_']. "
</option>";
}
}
?>
</select>
<span class="help-block"><?php echo $condition_err;?></span>
</div>
<div class="form-group <?php echo (!empty($producttype_err)) ? 'has-
error' : ''; ?>">
<label>Product</label>
</br>
<select name="producttype" class="form-control" value="<?php echo
$producttype ;?>">
<?php if($result4 = $mysqli ->query($sql4)){
while($row = $result4->fetch_array()){
echo "<option value=".$row['producttype'].">" .$row['producttype']. "
</option>";
}
}
?>
</select>
<span class="help-block"><?php echo $manufacturer_err;?></span>
</div>
So when I submit it return as the condition and producttype are empty. I think the error is because of
}
// Close connection
$mysqli->close();
}
statement that already close. But I don't know to place it.
PHP Warning: mysqli::query(): Couldn't fetch mysqli in /home/my-path/application/create_new.php on line 173
You should debug the html form first by right click with 'Inspect element' and make sure that the 'Select' value is getting?

bind_param(): variables != parameters [duplicate]

This question already has answers here:
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
(2 answers)
Closed 1 year ago.
I've just been trying to get this working for about 2 hours now, I can't understand what I'm doing wrong.
This is the error I'm getting :
Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement in /demo/records.php on line 117
also here:
<?php
/*
Allows the user to both create new records and edit existing records
*/
// connect to the database
include("connect-db.php");
// creates the new/edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($emri = '', $cmimi ='', $error = '', $id = '')
{ ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
<?php if ($id != '') { echo "Edit Record"; } else { echo "New Record"; } ?>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1><?php if ($id != '') { echo "Edit Record"; } else { echo "New Record"; } ?></h1>
<?php if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
. "</div>";
} ?>
<form action="" method="post">
<div>
<?php if ($id != '') { ?>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<p>ID: <?php echo $id; ?></p>
<?php } ?>
<strong>vEmri: *</strong> <input type="text" name="vEmri"
value="<?php echo $emri; ?>"/><br/>
<strong>vCmimi: *</strong> <input type="text" name="vCmimi"
value="<?php echo $cmimi; ?>"/>
<p>* required</p>
<input type="submit" name="submit" value="Submit" />
</div>
</form>
</body>
</html>
<?php }
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['id']))
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id']))
{
// get variables from the URL/form
$id = $_POST['id'];
$vEmri = htmlentities($_POST['vEmri'], ENT_QUOTES);
$vCmimi= htmlentities($_POST['vCmimi'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($vEmri == '' || $vCmimi == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($vEmri, $vCmimi, $error, $id);
}
else
{
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE veturat SET vEmri = ?, vCmimi= ?
WHERE id=?"))
{
$stmt->bind_param("ssi", $vEmri, $vCmimi, $id);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: view.php");
}
}
// if the 'id' variable is not valid, show an error message
else
{
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else
{
// make sure the 'id' value is valid
if (is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// get 'id' from URL
$id = $_GET['id'];
// get the recod from the database
if($stmt = $mysqli->prepare("SELECT * FROM veturat WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $vEmri, $vCmimi);
$stmt->fetch();
// show the form
renderForm($vEmri, $vCmimi, NULL, $id);
$stmt->close();
}
// show an error if the query has an error
else
{
echo "Error: could not prepare SQL statement";
}
}
// if the 'id' value is not valid, redirect the user back to the view.php page
else
{
header("Location: view.php");
}
}
}
/*
NEW RECORD
*/
// if the 'id' variable is not set in the URL, we must be creating a new record
else
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// get the form data
$vEmri= htmlentities($_POST['vEmri'], ENT_QUOTES);
$vCmimi = htmlentities($_POST['vCmimi'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($vEmri == '' || $vCmimi == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($vEmri, $vCmimi, $error);
}
else
{
// insert the new record into the database
if ($stmt = $mysqli->prepare("INSERT veturat (vEmri, vCmimi) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $vEmri, $vCmimi);
$stmt->execute();
$stmt->close();
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare SQL statement.";
}
// redirec the user
header("Location: view.php");
}
}
// if the form hasn't been submitted yet, show the form
else
{
renderForm();
}
}
// close the mysqli connection
$mysqli->close();
?>
Define the columns fetched explicitly. This should work (line 112):
// get the record from the database
if($stmt = $mysqli->prepare("SELECT id, vEmri, vCmimi, vNgjyra, vLenda, vTransmisioni, vKilometra, vProdhimi, vVellimi FROM veturat WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $vEmri, $vCmimi, $vNgjyra, $vLenda, $vTransmisioni, $vKilometra, $vProdhimi, $vVellimi);
$stmt->fetch();
// show the form
renderForm($vEmri, $vCmimi, NULL, $id);
$stmt->close();
}
You must have the same number of arguments in $stmt->bind_result() as the number of columns your SELECT query is fetching.

Update / Add new record does not work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am using this tutorial(http://www.killersites.com/community/index.php?/topic/3064-basic-php-system-view-edit-add-delete-records-with-mysqli/) and I followed every step required in order to create new records into the database but I cannot get update/edit to successfully update my database. I know that the code is not for html5 but I will fix that later. Additionally, retrieve & delete works.
What am I doing wrong? Why is it not working? Any help is greatly appreciated.
Also my table is structured like this,
Table: supplyDetails
Columns:
id int(11) AI PK
localAuthority varchar(50)
supplyRef varchar(50)
supplyName varchar(50)
estimatedDailyWater varchar(10)
numberOfConsumers varchar(45)
dateOfAssessment date
mitigatedRating varchar(2)
finalRating varchar(2)
Here is my records.php
<?php
/*
Allows the user to both create new records and edit existing records
*/
// connect to the database
include("connect-db.php");
// creates the new/edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($localauth = '', $supref = '', $supname = '', $waterusage = '', $numofconsum = '', $dateofassess = '', $mitrating = '', $frating = '', $error = '', $id = '') {
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
<?php
if ($id != '') {
echo "Edit Record";
} else {
echo "New Record";
}
?>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1>
<?php
if ($id != '') {
echo "Edit Record";
} else {
echo "New Record";
}
?>
</h1>
<?php
if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
. "</div>";
}
?>
<form action="" method="post">
<div>
<?php
if ($id != '') {
?>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<p>ID: <?php echo $id; ?></p>
<?php } ?>
<label>Local Authority: *</label>
<input type="text" name="localAuthority" value="<?php echo $localauth; ?>"/>
<br/>
<label>Supply Reference: *</label>
<input type="text" name="supplyRef" value="<?php echo $supref; ?>"/>
<br/>
<label>Supply Name: *</label>
<input type="text" name="supplyName" value="<?php echo $supname; ?>"/>
<br/>
<label>Estimated Daily Water Usage: *</label>
<input type="text" name="estimatedDailyWater" value="<?php echo $waterusage; ?>"/>
<br/>
<label>Number of Consumers: *</label>
<input type="text" name="numberOfConsumers" value="<?php echo $numofconsum; ?>"/>
<br/>
<label>Date of Assessment: *</label>
<input type="date" name="dateOfAssessment" value="<?php echo $dateofassess; ?>"/>
<br/>
<label>Mitigated Rating: *</label>
<input type="text" name="mitigatedRating" value="<?php echo $mitrating; ?>"/>
<br/>
<label>Final Rating: *</label>
<input type="text" name="finalRating" value="<?php echo $frating; ?>"/>
<p>* required</p>
<input type="submit" name="submit" value="Submit" />
</div>
</form>
</body>
</html>
<?php
}
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['id'])) {
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit'])) {
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id'])) {
// get variables from the URL/form
$id = $_POST['id'];
$localAuthority = htmlentities($_POST['localAuthority'], ENT_QUOTES);
$supplyRef = htmlentities($_POST['supplyRef'], ENT_QUOTES);
$supplyName = htmlentities($_POST['supplyName'], ENT_QUOTES);
$estimatedDailyWater = htmlentities($_POST['estimatedDailyWater'], ENT_QUOTES);
$numberOfConsumers = htmlentities($_POST['numberOfConsumers'], ENT_QUOTES);
$dateOfAssessment = htmlentities($_POST['dateOfAssessment'], ENT_QUOTES);
$mitigatedRating = htmlentities($_POST['mitigatedRating'], ENT_QUOTES);
$finalRating = htmlentities($_POST['finalRating'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($localAuthority == '' || $supplyRef == '' || $supplyName == '' || $estimatedDailyWater == '' || $numberOfConsumers == '' || $dateOfAssessment == '' || $mitigatedRating == '' || $finalRating == '') {
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($localAuthority, $supplyRef, $supplyName, $estimatedDailyWater, $numberOfConsumers, $dateOfAssessment, $mitigatedRating, $finalRating, $error, $id);
} else {
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE supplyDetails SET localAuthority = ?, supplyRef = ?, supplyName = ?, estimatedDailyWater = ?, numberOfConsumers = ?, dateOfAssessment = ?, mitigatedRating = ?, finalRating = ? WHERE id=?")) {
$stmt->bind_param("sssssdssi", $localAuthority, $supplyRef, $supplyName, $estimatedDailyWater, $numberOfConsumers, $dateOfAssessment, $mitigatedRating, $finalRating, $id);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else {
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: view.php");
}
}
// if the 'id' variable is not valid, show an error message
else {
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else {
// make sure the 'id' value is valid
if (is_numeric($_GET['id']) && $_GET['id'] > 0) {
// get 'id' from URL
$id = $_GET['id'];
// get the recod from the database
if($stmt = $mysqli->prepare("SELECT * FROM supplyDetails WHERE id=?")) {
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $localAuthority, $supplyRef, $supplyName, $estimatedDailyWater, $numberOfConsumers, $dateOfAssessment, $mitigatedRating, $finalRating);
$stmt->fetch();
// show the form
renderForm($localAuthority, $supplyRef, $supplyName, $estimatedDailyWater, $numberOfConsumers, $dateOfAssessment, $mitigatedRating, $finalRating, NULL, $id);
$stmt->close();
}
// show an error if the query has an error
else {
echo "Error: could not prepare SQL statement";
}
}
// if the 'id' value is not valid, redirect the user back to the view.php page
else {
header("Location: view.php");
}
}
}
/*
NEW RECORD
*/
// if the 'id' variable is not set in the URL, we must be creating a new record
else {
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit'])) {
// get the form data
$localAuthority = htmlentities($_POST['localAuthority'], ENT_QUOTES);
$supplyRef = htmlentities($_POST['supplyRef'], ENT_QUOTES);
$supplyName = htmlentities($_POST['supplyName'], ENT_QUOTES);
$estimatedDailyWater = htmlentities($_POST['estimatedDailyWater'], ENT_QUOTES);
$numberOfConsumers = htmlentities($_POST['numberOfConsumers'], ENT_QUOTES);
$dateOfAssessment = htmlentities($_POST['dateOfAssessment'], ENT_QUOTES);
$mitigatedRating = htmlentities($_POST['mitigatedRating'], ENT_QUOTES);
$finalRating = htmlentities($_POST['finalRating'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($localAuthority == '' || $supplyRef == '' || $supplyName == '' || $estimatedDailyWater == '' || $numberOfConsumers == '' || $dateOfAssessment == '' || $mitigatedRating == '' || $finalRating == '') {
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($localAuthority, $supplyRef, $supplyName, $estimatedDailyWater, $numberOfConsumers, $dateOfAssessment, $mitigatedRating, $finalRating, $error);
} else {
// insert the new record into the database
if ($stmt = $mysqli->prepare("INSERT supplyDetails (localAuthority, supplyRef, supplyName, estimatedDailyWater, numberOfConsumers, dateOfAssessment, mitigatedRating, finalRating)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)")) {
$stmt->bind_param("sssssdss", $localAuthority, $supplyRef, $supplyName, $estimatedDailyWater, $numberOfConsumers, $dateOfAssessment, $mitigatedRating, $finalRating);
$stmt->execute();
$stmt->close();
}
// show an error if the query has an error
else {
echo "ERROR: Could not prepare SQL statement.";
}
// redirec the user
header("Location: view.php");
}
}
// if the form hasn't been submitted yet, show the form
else {
renderForm();
}
}
// close the mysqli connection
$mysqli->close();
?>
view.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1>View Records</h1>
<p><b>View All</b> | View Paginated</p>
<?php
// connect to the database
include('connect-db.php');
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM supplyDetails ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table border='1' cellpadding='10'>";
// set table headers
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Local Authority</th>";
echo "<th>Supply Reference</th>";
echo "<th>Supply Name</th>";
echo "<th>Estimated Daily Water Usage</th>";
echo "<th>Number of Consumers</th>";
echo "<th>Date of Assessment</th>";
echo "<th>Mitigated Rating</th>";
echo "<th>Final Rating</th>";
echo "<th></th><th></th></tr>";
while ($row = $result->fetch_object())
{
// set up a row for each record
echo "<tr>";
echo "<td>" . $row->id . "</td>";
echo "<td>" . $row->localAuthority . "</td>";
echo "<td>" . $row->supplyRef . "</td>";
echo "<td>" . $row->supplyName . "</td>";
echo "<td>" . $row->estimatedDailyWater . "</td>";
echo "<td>" . $row->numberOfConsumers . "</td>";
echo "<td>" . $row->dateOfAssessment . "</td>";
echo "<td>" . $row->mitigatedRating . "</td>";
echo "<td>" . $row->finalRating . "</td>";
echo "<td><a href='records.php?id=" . $row->id . "'>Edit</a></td>";
echo "<td><a href='delete.php?id=" . $row->id . "'>Delete</a></td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
?>
Add New Record
</body>
</html>
connect-db.php
<?php
// server info
$server = 'localhost:3306';
$user = 'root';
$pass = '*****';
$db = 'test';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);
?>
SOLUTION for future references.
OK, I managed to come up with an answer. I implemented a proper error handler, thanks to the suggestions above, into my connect-db.php file
mysqli_report(MYSQLI_REPORT_ALL) ;
try {
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
} catch (Exception $e) {
echo $e->getMessage();
}
After fiddling around with editing a record, I was receiving an error regarding the date, so I changed the date type in my mysql table and from date -> varchar (30). (30 may be a lot for a date but meh)
Then I changed my code a bit to reflect those changes,
$dateOfAssessment = htmlentities($_POST['dateOfAssessment'], ENT_QUOTES);
$displaydate = date("D d M Y", strtotime($dateOfAssessment));
And also changed the $stmt to
if ($stmt = $mysqli->prepare("UPDATE supplyDetails SET localAuthority = ?, supplyRef = ?, supplyName = ?, estimatedDailyWater = ?, numberOfConsumers = ?, dateOfAssessment = ?, mitigatedRating = ?, finalRating = ? WHERE id=?")) {
$stmt->bind_param("ssssssssi", $localAuthority, $supplyRef, $supplyName, $estimatedDailyWater, $numberOfConsumers, $displaydate, $mitigatedRating, $finalRating, $id);
$stmt->execute();
$stmt->close();
}
And the output is something like this:
Sat 06 Aug 2016
Thanks everyone who had the time to reply.
OK, I managed to come up with an answer. I implemented a proper error handler, thanks to the suggestions above, into my connect-db.php file
mysqli_report(MYSQLI_REPORT_ALL) ;
try {
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
} catch (Exception $e) {
echo $e->getMessage();
}
After fiddling around with editing a record, I was receiving an error regarding the date, so I changed the date type in my mysql table and from date -> varchar (30). (30 may be a lot for a date but meh)
Then I changed my code a bit to reflect those changes,
$dateOfAssessment = htmlentities($_POST['dateOfAssessment'], ENT_QUOTES);
$displaydate = date("D d M Y", strtotime($dateOfAssessment));
And also changed the $stmt to
if ($stmt = $mysqli->prepare("UPDATE supplyDetails SET localAuthority = ?, supplyRef = ?, supplyName = ?, estimatedDailyWater = ?, numberOfConsumers = ?, dateOfAssessment = ?, mitigatedRating = ?, finalRating = ? WHERE id=?")) {
$stmt->bind_param("ssssssssi", $localAuthority, $supplyRef, $supplyName, $estimatedDailyWater, $numberOfConsumers, $displaydate, $mitigatedRating, $finalRating, $id);
$stmt->execute();
$stmt->close();
}
And the output is something like this:
Sat 06 Aug 2016
Thanks everyone who had the time to reply.

Updating SQL with form and PHP. Values resetting to 0 on submit?

I am attempting to create a simple form that updates a row in a MYSQL database based on what ID the row is.
I have managed to get the form and updating values working, but for one of my variables I need its new value to be added to it, based on the values of two other variables. (So like $currPoints = $currPoints+$addPoints-$remPoints;).
The problem I am facing is that whenever the form is submitted, $currPoints is either resetting to 0, then adding and subtracting the other values, or the value of $cuurPoints isn't being found so that it cannot add to it's original value.
I am not sure where specifically in my code I am going wrong so I will paste the whole page if that is okay!
My form function. This get's called on page load:
// creates the form
function renderForm($name = '', $currPoints = '', $addPoints = '', $remPoints = '', $reason = '', $error = '', $id = '')
{ ?>
<title>
<?php if ($id != '') { echo "Edit Punk"; } else { echo "New Punk"; } ?>
</title>
<h1><?php if ($id != '') { echo "Edit Punk"; } else { echo "New Punk"; } ?></h1>
<?php if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
. "</div>";
} ?>
<form name="pointsForm" action="" method="post" style="margin-top:50px;">
<?php if ($id != '') { ?>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<p>Name: <?php echo $name; ?> / <?php echo $currPoints; ?></p>
<?php } ?>
<input type="number" name="addPoints" placeholder="Add Punk Points">
<input type="number" name="remPoints" placeholder="Remove Punk Points">
<input type="text" name="reason" placeholder="Reason">
<input type="submit" name="submit" value="Update Punk Points">
</form>
</body>
</html>
<script>
$(function() {
$('form[name="pointsForm"]').submit(function(e) {
var reason = $('form[name="pointsForm"] input[name="reason"]').val();
if ( reason == '') {
e.preventDefault();
window.alert("Enter a reason, fool!")
}
});
});
</script>
<?php
}
Then my PHP for editing a record:
Where I get the variables from the URL/form I have added $currPoints = $currPoints+$addPoints-$remPoints;
Then on my bind_param is just add $currPoints.
I believe I am going wrong somewhere around these lines... or where I SET currPoints = ? . should that be something else?
Forgive me I am just learning PHP.
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['id']))
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id']))
{
// get variables from the URL/form
$id = $_POST['id'];
$addPoints = htmlentities($_POST['addPoints'], ENT_QUOTES);
$remPoints = htmlentities($_POST['remPoints'], ENT_QUOTES);
$reason = htmlentities($_POST['reason'], ENT_QUOTES);
$currPoints = $currPoints+$addPoints-$remPoints;
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE points SET currPoints = ? , addPoints = ?, remPoints = ?, reason = ?
WHERE id=?"))
{
$stmt->bind_param("iiisi", $currPoints, $addPoints, $remPoints, $reason, $id);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: index.php");
}
// if the 'id' variable is not valid, show an error message
else
{
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else
{
// make sure the 'id' value is valid
if (is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// get 'id' from URL
$id = $_GET['id'];
// get the record from the database
if($stmt = $mysqli->prepare("SELECT * FROM points WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $name, $currPoints, $addPoints, $remPoints, $reason, $date);
$stmt->fetch();
// show the form
renderForm($name, $currPoints, $addPoints, $remPoints, $reason, NULL, $id);
$stmt->close();
}
// show an error if the query has an error
else
{
echo "Error: could not prepare SQL statement";
}
}
// if the 'id' value is not valid, redirect the user back to the view.php page
else
{
header("Location: index.php");
}
}
}
?>
Sorry If I have been too vague. Please let me know if you need more information.
Thank you!
Oh found the error I think, you are never defining $currPoints before you try and use it, so you can't have $currPoints = $currPoints+.. because it isn't created yet. PHP more or less so will read line by line, so you have to query the SQL table and set $currPoints equal to the value from your database before you do $currPoints = $currPoints+$addPoints-$remPoints;
Ok, this probably won't work, but you should be able to figure out what I changed and adapt your code to work with it. I wouldn't say it's the 'proper' way, but it is a little easier to read and see what the code is doing when you have the if statements at the top to deal with what data is submitted vs not submitted.
if (!isset($_GET['id'] || !isset($_POST['submit'])))
{
echo "No Data!"
return;
}
if (!is_numeric($_POST['id']))
{
echo "Invalid ID!";
header("Location: index.php");
return;
}
// get variables from the URL/form
$id = $_POST['id'];
$addPoints = htmlentities($_POST['addPoints'], ENT_QUOTES);
$remPoints = htmlentities($_POST['remPoints'], ENT_QUOTES);
$reason = htmlentities($_POST['reason'], ENT_QUOTES);
$currPoints = 0;
//Check what the current points are first
// make sure the 'id' value is valid also
if (is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// get 'id' from URL
$id = $_GET['id'];
// get the record from the database
if($stmt = $mysqli->prepare("SELECT * FROM points WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $name, $currPoints, $addPoints, $remPoints, $reason, $date);
$stmt->fetch();
// show the form
renderForm($name, $currPoints, $addPoints, $remPoints, $reason, NULL, $id);
$stmt->close();
}
else
echo "Error: could not prepare SQL statement";
}
//Now update currPoints
$currPoints += $addPoints-$remPoints;
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE points SET currPoints = ? , addPoints = ?, remPoints = ?, reason = ?
WHERE id=?"))
{
$stmt->bind_param("iiisi", $currPoints, $addPoints, $remPoints, $reason, $id);
$stmt->execute();
$stmt->close();
}
else
echo "ERROR: could not prepare SQL statement.";
// redirect the user once the form is updated
header("Location: index.php");

PHP : Not able to show value retrieved from database into dropdown

I have an Task creation - View - Edit page. Once I create the task and user wants to edit it. He clicks edit button. So the value gets populated according to id. All the value gets populated except for Dropdown.:
This are my dropdowns :
<b>Assignee: &nbsp &nbsp &nbsp &nbsp </b><select name = "assignee" value = <?php echo $assignee ?></select>
<b>Priority:</b><select name = "priority" value= "<?php echo $priority; ?>" id="priority"><option>Low</option><option>Medium </option><option>High</option></select>
<b>Status: </b><select name = "status" value= "<?php echo $status; ?>" ><option>Assigned</option><option>Yet to Start </option><option>In Progress</option><option>Completed</option><option>Blocked</option></select>
This is code for getting the values and showing in table and updating to database
<?PHP
function renderForm($id, $task, $comments, $assignee, $priority, $status, $dataum1, $dataum2, $error) {/connecttothedatabaseinclude ('configdb1.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'];
$task = $_POST['task'];
$comments = $_POST['comments'];
$assignee = $_POST['assignee'];
$priority = $_POST['priority'];
$status = $_POST['status'];
$dataum1 = $_POST['dataum1'];
$dataum2 = $_POST['dataum2'];
// check that firstname/lastname fields are both filled in
if ($task == '' || $comments == '') {
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $task, $comments, $assignee, $priority, $status, $dataum1, $dataum2, $error);
} else {
// save the data to the database
mysql_query("UPDATE work SET task='$task', comments='$comments', assignee='$assignee', priority='$priority', status='$status', dataum1='$dataum1', dataum2='$dataum2' 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 work 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
// get data from db
$task = $row['assignee'];
$comments = $row['2'];
$assignee = $row['assignee'];
$priority = $row['priority'];
$status = $row['status'];
$dataum1 = $row['dataum1'];
$dataum2 = $row['dataum2'];
// show form
renderForm($id, $task, $comments, $assignee, $priority, $status, $dataum1, $dataum2, '');
} 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!';
}
}
?>
The select element does not have a value attribute - the selected option has a selected attribute.
In other words, you want something like:
<select name = "priority" id="priority">
<option <?php if ($priority == 'Low') { echo 'selected="selected"'; } ?>>Low</option>
<option <?php if ($priority == 'Medium') { echo 'selected="selected"'; } ?>>Medium </option>
<option <?php if ($priority == 'High') { echo 'selected="selected"'; } ?>>High</option>
</select>

Categories