使用PHP立即更新数据库中的所有字段

时间:2015-04-25 14:00:13

标签: php mysql pdo

我有一个来自表中链接的表单,该表只能更新数据库中的一条记录。当我更改表格中的一些细节并按下我的提交按钮时,它改变了我在数据库中的所有字段,而不仅仅是我想要更改的字段。下面是我的表单代码以及正在编辑的表。

修改用户代码

<?php

 // since this form is used multiple times in this file, I have made it a function that is easily reusable
 function renderForm($userID, $username, $password, $telephone, $address1, $town, $postcode, $forename, $surname, $email, $error)
 {
 ?>
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
 <html>
 <head>
 <title>Edit User</title>
 </head>
 <body>
 <?php 
 // if there are any errors, display them
 if ($error != '')
 {
 echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
 }
 ?> 
 
 <form action="" method="post">
 <input type="hidden" name="userID" value="<?php echo $userID; ?>"/>
 <div>
 <p><strong>ID:</strong> <?php echo $userID; ?></p>
 <strong>Username: </strong> <input type="text" name="username" value="<?php echo $username; ?>"/><br/>
 <strong>Password: </strong> <input type="text" name="password" value="<?php echo $password; ?>"/><br/>
 <strong>Telephone: </strong> <input type="text" name="telephone" value="<?php echo $telephone; ?>"/><br/>
 <strong>Address: </strong> <input type="text" name="address1" value="<?php echo $address1; ?>"/><br/>
 <strong>Town: </strong> <input type="text" name="town" value="<?php echo $town; ?>"/><br/>
 <strong>Postcode: </strong> <input type="text" name="postcode" value="<?php echo $postcode; ?>"/><br/>
 <strong>Forename: </strong> <input type="text" name="forename" value="<?php echo $forename; ?>"/><br/>
 <strong>Surname: </strong> <input type="text" name="surname" value="<?php echo $surname; ?>"/><br/>
 <strong>Email: </strong> <input type="text" name="email" value="<?php echo $email; ?>"/><br/>

 <input type="submit" name="submit" value="Edit details">
 </div>
 </form> 
 </body>
 </html> 
 <?php
 }



 // connect to the database
 include "config.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['userID']))
 {
 // get form data, making sure it is valid
 $userID = $_POST['userID'];
 $username = $_POST['username'];
 $password = $_POST['password'];
 $telephone = $_POST['telephone'];
 $address1 = $_POST['address1'];
 $town = $_POST['town'];
 $postcode = $_POST['postcode'];
 $forename = $_POST['forename'];
 $surname = $_POST['surname'];
 $email = $_POST['email'];
 
 // check that firstname/lastname fields are both filled in
 if ($username == '' || $password == '' || $telephone == '' || $address1 == '' || $town == '' || $postcode == '' || $forename == '' || $surname == '' || $email == '' )
 {
 // generate error message
 $error = 'ERROR: Please fill in all required fields!';
 
 //error, display form
 renderForm($userID, $username, $password, $telephone, $address1, $town, $postcode, $forename, $surname, $email, $error);
 }
 else
 {
 // save the data to the database
 	$query = $db->prepare("UPDATE user SET username='$username', password='$password', telephone='$telephone', address1='$address1', town='$town', postcode='$postcode', forename='$forename', surname='$surname', email='$email' ");
	$query->execute();
 
 // once saved, redirect back to the view page
 header("Location: view_user.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['userID']) && is_numeric($_GET['userID']) && $_GET['userID'] > 0)
 {
 // query db
 $userID = $_GET['userID'];
 $query = $db->prepare("SELECT * FROM user WHERE userID=$userID");
 $query->execute();
 $dbRow = $query->fetch(PDO::FETCH_ASSOC);
 
 // check that the 'id' matches up with a row in the databse
 if($dbRow)
 {
 
 // get data from db
 $username = $dbRow['username'];
 $password = $dbRow['password'];
 $telephone = $dbRow['telephone'];
 $address1 = $dbRow['address1'];
 $town = $dbRow['town'];
 $postcode = $dbRow['postcode'];
 $forename = $dbRow['forename'];
 $surname = $dbRow['surname'];
 $email = $dbRow['email'];
 
 
 // show form
 renderForm($userID, $username, $password, $telephone, $address1, $town, $postcode, $forename, $surname, $email, '');
 }
 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!';
 }
 }
?>

查看用户信息代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Ballymena Sports</title>

    <!-- Bootstrap core CSS -->
    <link href="bootstrap.min.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="home2.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>

  <body>

    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
      <div class="container">
        <div class="navbar-header">
				<a class="navbar-brand" href="home2_template.html">Ballymena Sports</a>
		</div>
		
		<ul class="nav navbar-nav navbar-right">
		    <li><a href="admin_login.php">Administrator</a></li>
            <li><a href="logout.php">Log out</a></li>
		</ul>
		
	  </div>
    </nav>
	


    <!-- Main part of homepage -->
    <div class="jumbotron">
		<div class="container">
		  <h2>Users</h2>
		  <p>This table shows all registered users of Ballymena Sports:</p>            
			
			<div class="table-responsive"> 
			<tbody>
				<?php 
					include "config.php"; 
					
					$query = $db->prepare("SELECT * FROM user ORDER BY userID asc");
					$query->execute();
		
		
					echo "<table id='user' class='table table-bordered'>
						  <tr>
						  <th>User ID</th>
						  <th>Username</th>
						  <th>Forename</th>
						  <th>Surname</th>
						  <th>Email</th>
						  <th>Address</th>
						  <th>Town</th>
						  <th>Postcode</th>
						  <th>Edit User</th> 
						  <th>Delete User</th>
						  </tr>";
						
					while ($dbRow = $query->fetch(PDO::FETCH_ASSOC)) {
						$userID = $dbRow['userID'];
						$username = $dbRow['username'];
						$forename = $dbRow['forename'];
						$surname = $dbRow['surname'];
						$email = $dbRow['email'];
						$address1 = $dbRow['address1'];
						$town = $dbRow['town'];
						$postcode = $dbRow['postcode'];
						// code to display information
						
				
			   { echo "<tr>
						<td>$userID</td>
						<td>$username</td>
						<td>$forename</td>
						<td>$surname</td>
						<td>$email</td>
						<td>$address1</td>
						<td>$town</td>
						<td>$postcode</td>
						<td><a href='edit_user.php?userID=".$userID."'>Edit</a></td>
						<td><a href='delete_user.php?userID=".$userID."'>Delete</a></td>
					  </tr>";}
				} //while
				?> 

			</tbody>
			</div>
		  </table>
		</div>
    </div>
<?php 


	if(!$_SESSION['admin_username']){
		header('location:admin_login.php'); 
		
		$name = $_SESSION['admin_username'];
	}
	
?> 

      <hr>



    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="../../dist/js/bootstrap.min.js"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="../../assets/js/ie10-viewport-bug-workaround.js"></script> 
	<!-- Header and footer later to be used as include statements -->
  </body>
</html>

2 个答案:

答案 0 :(得分:2)

您的问题是您的update语句未指定where子句:

$query = $db->prepare("UPDATE user SET username='$username', password='$password', telephone='$telephone', address1='$address1', town='$town', postcode='$postcode', forename='$forename', surname='$surname', email='$email' ");

您需要使用用户ID指定您只想更新此特定用户的行:

$query = $db->prepare("UPDATE user SET username='$username', password='$password', telephone='$telephone', address1='$address1', town='$town', postcode='$postcode', forename='$forename', surname='$surname', email='$email' where userId=$userID");

您还应该考虑使用预准备语句来保护代码免受SQL注入攻击。

答案 1 :(得分:0)

你需要检查query.missing更新query.try中的where子句

$ query = $ db-&gt; prepare(“UPDATE user SET username ='$ username',password ='$ password',telephone ='$ telephone',address1 ='$ address1',town ='$ town ',postcode ='$ postcode',forename ='$ forename',surname ='$ surname',email ='$ email',其中userId = $ userID“);