I'm trying to build an HTML form to update a MySQL database using PHP. When I load the page, the table populates exactly as I intend for it. However, when I change something in one of the text boxes and click the update button, the change doesn't get posted to the database. It just reloads the database into the form/table right where I began. For reference, the name
field is just a concatenation of first
and last
I use as the primary key/id. Where did I go wrong?
<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>