I'm working on a basic database app which uses a sql database to store and retrieve information from as part of the crud operations the creation and reading of data works perfectly fine. However I'm facing issues with updating and deleting the data stored and it never happened before.Is there something I'm doing wrong?
I'm assuming the something that I've done wrong in update may be similar to my issue in delete.
Here's the code for the update part : [Note this is just for a basic demo and so security features aren't important]
<?php
require "config.php";
require "common.php";
if (isset($_POST['submit'])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$user =[
"char_id" => $_POST['char_id'],
"char_name" => $_POST['char_name'],
"currency" => $_POST['currency'],
"server_id" => $_POST['server_id'],
"account_id" => $_POST['account_id']
];
$sql = "UPDATE characters
SET
char_name = :char_name,
currency = :currency,
server_id = :server_id,
account_id = :account_id
WHERE char_id = :char_id";
$statement = $connection->prepare($sql);
$statement->execute($user);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
if (isset($_GET['char_id'])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$char_id = $_GET['char_id'];
$sql = "SELECT * FROM characters WHERE char_id = :char_id";
$statement = $connection->prepare($sql);
$statement->bindValue(':char_id', $char_id);
$statement->execute();
$user = $statement->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
} else {
echo "Something went wrong!"; //this happens
exit;
}
?>
<?php require "templates/header.php"; ?>
<?php if (isset($_POST['submit']) && $statement) : ?>
<blockquote><?php echo escape($_POST['char_name']); ?> successfully
updated.</blockquote>
<?php endif; ?>
<h2>Edit a character</h2>
<form method="post">
<?php foreach ($user as $key => $value) : ?>
<label for="<?php echo $key; ?>"><?php echo ucfirst($key); ?>
</label>
<input type="text" name="<?php echo $key; ?>" id="<?php echo $key; ?>" value="<?php echo escape($value); ?>" <?php echo ($key === 'id' ? 'readonly' : null); ?>>
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit">
</form>
Back to home
<?php require "templates/footer.php"; ?>
The problem seems to be that your loop of inputs expects an array variable called $user. The $user comes from a DB query, using inputs from your form, but the actual input values comes from the $user variable which isn't set until the DB query is run!
First I would try keeping the $_GET in your code. Your SELECT query expects $_GET['char_id'] to be set in order to execute. Do that by adding ?char_id=SOME NUMBER HERE to your url and go. The number should be a char_id present in your Database.
Now the DB query gets the $_GET['char_id'] that it needs (since the $_GET method fetches parameters from the URL), and you should get some working inputs from your loop, and be able to update entries in your Database.
I'm creating a simple PHP to do list. I want to turn the date red if it's not the current date. Here's part of my code, with the HTML removed:
<?php include "connection.php";?>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$task = isset($_POST['task']) ? $_POST['task'] : null;
$importance = isset($_POST['importance']) ? $_POST['importance'] : null;
$due_date = isset($_POST['due_date']) ? $_POST['due_date'] : null;
$order = isset($_POST['order']) ? $_POST['order'] : null;
if(isset($task,$importance,$due_date)){
$sql = "INSERT INTO tasks (task, importance, due_date) VALUES ('$task', '$importance', '$due_date')";
$result = mysqli_query($connection, $sql);
if(!$result){
die("Database query failed.");
}
}
}
if(isset($order)){
$sql = "SELECT * FROM tasks ORDER BY {$order}";
} else {
$sql = "SELECT * FROM tasks";
}
$result = mysqli_query($connection, $sql);
if(!$result){
die("Database query failed.");
}
$current_date = date("Y-m-d");
if(isset($due_date)!=$current_date){
$due_date_class="overdue";
} else {
$due_date_class="not_overdue";
}
?>
<table>
<?php
while($column = mysqli_fetch_assoc($result)){
?>
<tr><td><?php echo $column["task"]?></td><td class="<?php echo $column["importance"] ?>"><?php echo $column["importance"]?></td><td class="<?php echo $due_date_class ?>"><?php echo $column["due_date"]?></td><td><?php echo "<a href='delete_one.php?id=".$column['id']."'>Delete</a>" ?></td></tr>
<?php
}
?>
</table>
<?php include "footer.php";?>
This is the part that isn't working. It's either turning all the rows red or black, depending on what date I enter:
$current_date = date("Y-m-d");
if(isset($due_date)!=$current_date){
$due_date_class="overdue";
} else {
$due_date_class="not_overdue";
}
isset($due_date)
should be changed to
$due_date
Because, isset will return value 1 or 0, which will be compared with date, which is going to be false all the time.
Instead, you could do following:
if(isset($due_date))
{
$current_date = date("Y-m-d");
if($due_date!=$current_date){
$due_date_class="overdue";
} else {
$due_date_class="not_overdue";
}
}
else
{
echo "Not a valid Due Date";
}
>>>Demo<<<
Regarding variable scoping.
You need to declare $due_date_class at very top, to increase its scope, otherwise you will get error. Since, scope of this variable will be limited to if and else.
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.
I am trying to create a button on my user list page to delete that row, or make that user an admin.
Here is the info for the user query and html:
<?php
$query = "SELECT * FROM users";
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("An Error has occured. Please contact the server administrator for assistance.");
}
$rows = $stmt->fetchAll();
?>
<?php foreach($rows as $row) : ?>
<?php
if($row['usertype'] == 2) {
$usertype = "<span style='color:#F7FE2E;'>Donator</span>";
} elseif($row['usertype'] == 3) {
$usertype = "<span style='color:red;'>Admin</span>";
} elseif($row['usertype'] == 4) {
$usertype = "<span style='color:orange;'>Owner</span>";
} else {
$usertype = "<span style='color:#585858;'>Normal</span>";
}
?>
<tr>
<!--<td><?php echo $row['id']; ?></td>-->
<td><?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8');?></td>
<!--<td><?php echo htmlentities($row['email'], ENT_QUOTES, 'UTF-8');?></td>-->
<td><?php echo htmlentities($row['steamid'], ENT_QUOTES, 'UTF-8');?></td>
<td><?php echo $usertype?></td>
<td><form action="" method="post">
<input type="submit" name="admin" value="Promote" />
</form></td>
</tr>
<?php endforeach; ?>
And the code where I prepare and execute my update query:
if(!empty($_POST['admin']))
{
$query = "UPDATE `users` SET `usertype` = '3' WHERE `id` = " . $row['id'];
// $query_params = array(':id' => $row['id']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("An Error has occured. Please contact the server administrator for assistance.");
}
}
Unfortunately I when I run this current setup, it updates the very last row. To further ask what I am looking for, is I have a list of users:
where "admin_b" is a button that forced $_POST['admin']
Billy admin_b
Bob admin_b
Jill admin_b
Jack admin_b
UPDATE:
So in my form I have an input with <input type="hidden" name="id" value="<?php $row['id']; ?>" /> and added this to my SQL $query = "UPDATE users SET usertype = '3' WHERE id = :id"; $query_params = array(':id' => $_POST['id']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("An Error has occured. Please contact the server administrator for assistance.");
}
send an id with $_POST request, now you are always update user with id = $row['id']
WHERE `id` = " . $row['id'];
row[id]edit?=edit.php= ...
and let's say you have list all the members and beside them is an href, the code above will execute, it will display let's say Billy?edit.php=1, wherein 1 is his primary key, then for the next, when you scroll the cursor to the next href of the next user, Jim, it will display, Jim?edit.php=2, in your edit.php,
if(isset($_POST['edit])){
code goes here to make the user an admin..
You can also make an href for the delete, similar to this edit..
This is just an idea/hint that I can give to you, but your problem can be solved in many different ways, it just depends on your approach on how you could do it :D goodluck.
I have two files .. addclient.php & Editclient.php.
I want to combine in one php form. can u please help me to do this
<?php
if(isset($_GET['id'])) {
$id = $_GET['id'];
echo "add";
} else if(isset($_GET['id'])) {
$id = $_GET['id'];
echo "edit"
}
?>
if $id already exist in the table than the row is updated otherwise it's an INSERT.
If you only have an $id : show the form with existing data in it.
If it's not a $id isn't populated : show an empty form.
<?php
if(isset($_GET['id'])) {
$id = intval($_GET['id']);
$stmt = $mysqli->prepare("SELECT id FROM table WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
if($stmt->num_rows > 0) {
// UPDATE
// Text field with the id
echo '<input type="text" name="id" value="'. $id. '"/>';
} else {
// INSERT
// Text field with no id
echo '<input type="text" name="id"/>';
}
}
?>
This validates the integer and makes sure it's one, queries the table for that specific id, if there is more than one row with that id then you need to update, else you need to insert.
<?php
if(isset($_GET['ID'])) {
$ID= $_GET['ID'];
// Use MySQL with $ID to check if the user is existing, and this string will either be 0 or 1
$existing = 0; // 0 = New 1 = Existing
//Add
if($existing== 0) {
}
//Edit
if($existing == 1) {
}
}
?>
Try this
<?php
if(isset($_GET['id'])) {
$id = $_GET['id'];
echo "update";
}else{
$id = $_GET['id'];
echo "add"
}
?>
Can you try this,
<?php
if(isset($_GET['id'])) {
$id = $_GET['id'];
echo "Edit";
} else {
echo "Add"
}
?>
try this
if(isset($id) && !empty($id)){
echo "Update";
}else{
echo "Add";
}