我正在尝试构建HTML表单以使用PHP更新MySQL数据库。当我加载页面时,表将完全按照我的预期进行填充。但是,当我在其中一个文本框中更改某些内容并单击“更新”按钮时,所做的更改不会发布到数据库中。它只是将数据库重新加载到我刚开始的表单/表中。作为参考,name
字段只是first
和last
的串联,我用作主键/ id。我哪里出错了?
<html>
<body>
<?php
define( 'DB_SERVER', '123.234.345.456' );
define( 'DB_USERNAME', 'subad' );
define( 'DB_PASSWORD', 'password' );
define( 'DB_NAME', 'membership' );
$link = mysqli_connect( DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if ( $link === false ) {die( "ERROR: Could not connect. " . mysqli_connect_error() );}
$sql = 'SELECT * FROM members WHERE county = "abc"';
$result = mysqli_query( $link, $sql )or die( "Error With $sql" );
?>
<?php
if(isset($_POST['update'])){
try{$pdo = new PDO("mysql:host=123.234.345.456;dbname=membership", "subad", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}
catch(PDOException $e){die("ERROR: Could not connect. " . $e->getMessage());}
try{
$first = $_POST['first'];
$last = $_POST['last'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$sql = "UPDATE members SET first=:first, last=:last, phone=:phone, email=:email WHERE name=:name";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(":first", $first, PDO::PARAM_STR);
$stmt->bindValue(":last", $last, PDO::PARAM_STR);
$stmt->bindValue(":phone", $phone, PDO::PARAM_STR);
$stmt->bindValue(":email", $email, PDO::PARAM_STR);
$stmt->bindValue(":name", $name, PDO::PARAM_STR);
$stmt->execute();}
catch(PDOException $e){die("ERROR: Could not able to execute $sql. " . $e->getMessage());}
}
unset($pdo);?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<?php while($row = mysqli_fetch_array($result)) {$first = $row['first']; $last = $row['last']; $email = $row['email']; $phone = $row['phone']; $name = $row['name']; ?>
<td width="100"></td>
<td><?=$name?></td>
</tr>
<tr>
<td width="100">First</td>
<td><input name="first" type="text" value="<?=$first?>"></td>
</tr>
<tr>
<td width="100">Last</td>
<td><input name="last" type="text" value="<?=$last?>"></td>
</tr>
<tr>
<td width="100">Email</td>
<td><input name="email" type="text" value="<?=$email?>"></td>
</tr>
<tr>
<td width="100">Phone</td>
<td><input name="phone" type="text" value="<?=$phone?>"></td>
</tr>
<?php } ?>
<tr>
<td>
<input name="update" type="submit" id="update" value="Update">
</td>
</tr>
</table>
</form>
</body>
</html>
答案 0 :(得分:0)
这对我来说不合适
<form method="post" action="<?php $_PHP_SELF ?>">
我看不到设置$_PHP_SELF
的位置,您实际上并没有回显它。另外,您可能会想到$_SERVER["PHP_SELF"]
,但这可能不是您想要的。尝试将操作保留为空,它将发布到当前网址:
<form method="post" action="">