I’m trying to follow Kevin Yank’s Sitepoint book, PHP & MYSQL: Novice to Ninja. I’m hitting a snag. When creating a page with a form showing the row contents in <input> fields (so the viewer can edit the table row contents in case he made a mistake), and its submit button returns the same page for insertion, is this the right skeleton to follow when using PDO? I’ve voiced a few of my doubts below in comments (page numbers refer to edition 5 of book for my reference):
/* If user has edited the form and pressed the submit button, do the following up to the else{ statement: */
<?php
$pdo = // ... connection stuff...
// p 125:
if (isset($_POST['xxxx_id']))
{
if (isset($_POST['xxxx1']))
if (isset($_POST['xxxx2']))
// Do I need all of the above in order to declare the values, or only the first one?
// (There's no "UPDATE ... SET" example in the book; follow same process as in INSERT?)
try
{
$sql = "UPDATE ... SET
xxxx1 = :xxxx1,
xxxx2 = :xxxx2
WHERE xxxx_id = :xxxx_id
";
$s = $pdo->prepare($sql);
$s->bindValue(':xxxx1', $_POST['xxxx1']);
$s->bindValue(':xxxx2', $_POST['xxxx2']);
$s->execute();
}
catch (PDOException $e)
{
echo 'Error performing update: ' . $e->getMessage();
exit();
}
echo 'Success! <a href="Provide link"> to another page.</a>'
} // end if isset
/* If submit button hasn't been pressed, show the form with fields filled out. */
// p 129:
else
{
if (isset($_POST['xxxx_id']))
if (isset($_POST['xxxx1']))
if (isset($_POST['xxxx2']))
// Do I need all of the above in order to declare the values, or only the first one?
try
{
$sql = "SELECT ...
xxxx1 = :xxxx1,
xxxx2 = :xxxx2
FROM ...
WHERE xxxx_id = :xxxx_id
";
$result = $pdo->query($sql);
}
catch (PDOException $e)
{
echo 'Error performing select statement: ' . $e->getMessage();
exit();
}
while ($row = $result->fetch())
{
$tabledata[] = $row['xxxx1'];
$tabledata[] = $row['xxxx2'];
}
/* ... NOT SURE WHAT GOES HERE TO FILL IN THE FOLLOWING FORM ... */
<form action="<?php echo $_SERVER['PHP_SELF']; ?>?xxxx_id=<?php echo $xxxx_id; ?>" method="post">
<label>Name: <input type="text" name="xxxx1" value="<?php echo htmlspecialchars($xxxx1, ENT_QUOTES, 'UTF-8') ?>"></label>
<label>Address: <input type="text" name="xxxx2" value="<?php echo htmlspecialchars($xxxx2, ENT_QUOTES, 'UTF-8') ?>"></label>
<input type="submit" value="Submit Changes">
</form>
} // end else
?>