Update / Add new record does not work [closed] - php

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.

Related

MYSQL SET UPDATE table from a variable re-asked [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 3 years ago.
Need to be able to UPDATE a MYSQL table with string data. Get errors no matter what I try, and I have researched and nothing suggested works in this situation.
'$soldout'
'"$soldout"'
{$soldout}
'{$soldout}'
'"{$soldout}"'
<?php
/**
* Use an HTML form to edit an entry in the
* consignitem table.
*
*/
require "../config.php";
require "../common.php";
if (isset($_POST['submit'])) {
if (!hash_equals($_SESSION['csrf'], $_POST['csrf'])) die();
try {
$connection = new PDO($dsn, $username, $password, $options);
$itemnumber = $_POST['itemnumber'];
$item =[
"itemnumber" => $_POST['itemnumber'],
"itemdescription" => $_POST['itemdescription'],
"reserve" => $_POST['reserve'],
"amount" => $_POST['amount'],
"qtyavail" => $_POST['qtyavail'],
"qtybought" => $_POST['qtybought'],
"buyernumber" => $_POST['buyernumber'],
"sold" => $_POST['sold'],
];
/* following is manipulation section including debug lines as echo of data*/
$qtyav = $_POST['qtyavail'];
$qtybo = $_POST['qtybought'];
$amt = $_POST['amount'];
echo "Quan Avail $qtyav<br>";
echo "Quan Bou $qtybo<br>";
echo "AMT $amt<br>";
$amttot = $qtybo * $amt;
echo "AMTTOT $amttot<br>";
$newqty = $qtyav - $_POST['qtybought'];
echo "NewQty $newqty<br>";
if ($newqty < "1") {
$soldout = "y";
echo "soldout $soldout<br>";
} else {
$soldout = "n";
echo "soldout $soldout<br>";
}
/* End Manipulation.
Try adding field for quantity available, then do math.
*/
$sql = "UPDATE consignitem
SET itemnumber = :itemnumber,
itemdescription = :itemdescription,
reserve = :reserve,
amount = :amount,
qtyavail = {$newqty},
qtybought = :qtybought,
buyernumber = :buyernumber,
sold = :sold
WHERE itemnumber = :itemnumber";
$statement = $connection->prepare($sql);
$statement->execute($item);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
if (isset($_GET['itemnumber'])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$itemnumber = $_GET['itemnumber'];
$sql = "SELECT * FROM consignitem WHERE itemnumber = :itemnumber AND sold = 'n'";
$statement = $connection->prepare($sql);
$statement->bindValue(':itemnumber', $itemnumber);
$statement->execute();
$item = $statement->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
} else {
echo "Something went wrong!";
exit;
}
?>
<?php require "templates/header.php"; ?>
<?php if (isset($_POST['submit']) && $statement) : ?>
<blockquote><?php echo escape($_POST['itemnumber']); ?> successfully updated.</blockquote>
<?php endif; ?>
<h2>Sell an item</h2>
<form method="post">
<style>
table, th, td {
border: 1px solid black;
}
</style>
<table>
<input name="csrf" type="hidden" value="<?php echo escape($_SESSION['csrf']); ?>">
<?php foreach ($item as $key => $value) : ?>
<tr><td><?php echo ucfirst($key); ?></td><td><input type="text" name="<?php echo $key; ?>" id="<?php echo $key; ?>" value="<?php echo escape($value); ?>" <?php echo ($key === 'serial' ? 'readonly' : null); ?><?php echo ($key === 'salenumber' ? 'readonly' : null); ?><?php echo ($key === 'itemnumber' ? 'readonly' : null); ?> <?php echo ($key === 'lotnumber' ? 'readonly' : null); ?><?php echo ($key === 'category' ? 'readonly' : null); ?><?php echo ($key === 'itemdescription' ? 'readonly' : null); ?><?php echo ($key === 'reserve' ? 'readonly' : null); ?><?php echo ($key === 'sellernumber' ? 'readonly' : null); ?><?php echo ($key === 'paid' ? 'readonly' : null); ?>></td></tr>
<?php endforeach; ?>
</table>
<?php echo ($key === 'itemnumber');?>
<br>
<button type="submit" name="submit"><b><h3>Sell the Item</h3></b></button>
</form>
<br>
Back to Item List<br>
<?php require "templates/footer.php"; ?>
UPDATED- - -
Original post:
In the section where sql = UPDATE SET:
Where it says sold = :sold,
I need it to take the variable $soldout and use it to update the field for sold in the table. The one above it for $newqty works fine but when I change the sold one from sold = :sold to sold = , I get an error about number of items doesn't match number of bound items or some such. And it doesn't update the table. Leaving it as sold = :sold works but just doesn't update the sold field.
I have researched using a string in there but nothing I try works.
I know my code is horrible, but this is the first time I have ever tried using PHP with a MYSQL database, and the first time ever to work with a MYSQL database at all. I know it is subject to injections and all that. . once I get it working, I can then figure out how to secure it better.
Thank you in advance!
UPDATED INFO - - -
This script works perfectly for every thing except changing the sold from 'n' to 'y' in the table.
The
qtyavail = {$newqty},
line works so why doesn't
sold = {$soldout}
work? It is the same format as the qtyavail one and the variable $soldout is set just a few lines from the qtyavail one but it is eluding me why it won't work.
Thanks again for any insight!
You don't have a :sold placeholder in the query. And you're calling bindValue() incorrectly; you should call it the same way for :sold as you do for :itemnumber.
$itemnumber = $_GET['itemnumber'];
$sql = "SELECT * FROM consignitem WHERE itemnumber = :itemnumber AND sold = :sold";
$statement = $connection->prepare($sql);
$statement->bindValue(':itemnumber', $itemnumber);
$statement->bindValue(':sold', $soldout);
$statement->execute();
You also have a problem with the UPDATE query. $item contains
"qtyavail" => $_POST['qtyavail'],
but the query contains
qtyavail = {$newqty},
You should change the query to
qtyavail = :qtyavail,
and set
$item['qtyavail'] = $newqty;
first of all check wrong quotes in"
$statement->bindValue(':sold, "{$soldout}"');
Most probably should be :
$statement->bindValue(':sold', "{$soldout}");

PHP MySQL row editor showing in wrong order

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=?"));

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.

Trying to insert into database using id from link and prepared statement

I currently have the following code. What I'm trying to do is fetch the oppdrID=x from the link and put the query into the row with the same oppdrID. I can't get it to work because something is not working. What am I dong wrong here?
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stilsett.php" />
<meta charset="utf-8">
<title>Endre oppdrag // Prosjekt - PHP</title>
</head>
<body>
<?php
include "funksjoner.inc.php";
session_start();
if(!empty($_SESSION['brukernavn'])) {
echo "<div id='header'>";
echo navigasjon();
echo "</div>";
echo "<div id='innhold'>";
$startTid = mysqli_real_escape_string(kobleTil(), htmlspecialchars($_POST['startTid']));
$slutTid = mysqli_real_escape_string(kobleTil(), htmlspecialchars($_POST['slutTid']));
$merknad = mysqli_real_escape_string(kobleTil(), htmlspecialchars($_POST['merknad']));
$antTimer = mysqli_real_escape_string(kobleTil(), htmlspecialchars($_POST['antTimer']));
if ($startTid == '' || $slutTid == '' || $merknad == '' || $antTimer == '') {
$error = "Vennligst fyll inn alle dataene!";
}
$db = kobleTil();
if (isset($_GET['oppdrID']) && is_numeric($_GET['oppdrID']) && $_GET['oppdrID'] > 0) {
$id = $_GET['oppdrID'];
$sql = "INSERT INTO timeregistrering WHERE oppdrID = ? (startTid, sluttTid, merknad, timer) values ('$startTid', '$slutTid', '$merknad', '$antTimer');
";
if ($stmt->prepare($sql)) {
$stmt->bind_param("i", $id, $startTid, $slutTid, $merknad, $antTimer);
$stmt->execute();
if ($db->query($sql)) {
echo "<p><b>Tabellen ble opprettet!</b></p>";
echo "<b>Spørringen som ble kjørt:</b><pre>$sql</pre>";
} else {
echo "<p>Noe gikk galt :(</p>" . $error;
}
}
}
}
echo "</div>";
?>
</body>
</html>
I think your prepared statement is wrong, try this instead:
$sql = "INSERT INTO timeregistrering(startTid, sluttTid, merknad, timer) values (?, ?, ?, ?)";
$stmt->bind_param($startTid, $slutTid, $merknad, $antTimer);
I removed the where clause because you can't use where on an insert unless it is where not exists

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");

Categories