更新/添加新记录不起作用

时间:2016-08-12 18:36:16

标签: php mysql mysqli

我正在使用本教程(http://www.killersites.com/community/index.php?/topic/3064-basic-php-system-view-edit-add-delete-records-with-mysqli/),我按照所需的每一步操作,以便在数据库中创建新记录,但我无法进行更新/编辑以成功更新我的数据库。我知道代码不适用于html5但我稍后会修复它。另外,检索&删除工作。

我做错了什么?为什么不起作用?任何帮助是极大的赞赏。

此外,我的表格结构如下,

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)

这是我的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> | <a href="view-paginated.php">View Paginated</a></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();

?>

<a href="records.php">Add New Record</a>
</body>
</html>

连接-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);

?>

解决方案以供将来参考。

好的,我设法得到了答案。由于上面的建议,我在connect-db.php文件中实现了一个合适的错误处理程序

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

在编辑记录后,我收到了关于日期的错误,因此我更改了mysql表中的日期类型,并从日期 - &gt; varchar(30)。 (30岁可能很多,但是meh)

然后我改变了我的代码以反映这些变化,

$dateOfAssessment = htmlentities($_POST['dateOfAssessment'], ENT_QUOTES);
$displaydate = date("D d M Y", strtotime($dateOfAssessment));

并将$stmt更改为

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

输出是这样的:

Sat 06 Aug 2016

感谢所有有时间回复的人。

1 个答案:

答案 0 :(得分:0)

好的,我设法得到了答案。由于上面的建议,我在connect-db.php文件中实现了一个合适的错误处理程序

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

在编辑记录后,我收到了关于日期的错误,因此我更改了mysql表中的日期类型,并从日期 - &gt; varchar(30)。 (30岁可能很多,但是meh)

然后我改变了我的代码以反映这些变化,

$dateOfAssessment = htmlentities($_POST['dateOfAssessment'], ENT_QUOTES);
$displaydate = date("D d M Y", strtotime($dateOfAssessment));

并将$stmt更改为

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

输出是这样的:

Sat 06 Aug 2016

感谢所有有时间回复的人。