I create a news section onn my website and want the ability to update it if needed. I had it working using the old mysql method, but want to change it by using PDO.
Can someone point out my error. The form pulls in data for me to update, but its pulling from the wrong row / id.
Here is my query:
<?php
$post_title = "";
$description = "";
$id = $_GET['id'];
$query = $db->query("SELECT title, description FROM htp_news WHERE id='$id'");
$post_title = $db->query('SELECT title FROM htp_news')->fetchColumn();
$description = $db->query('SELECT description FROM htp_news')->fetchColumn();
?>
And Here is my form where I'm echoing in the data.
<form method="post" action="update-news.php">
<input type="hidden" name="ud_id" style="width: 100%" value="<?php echo "$id"; ?>">
<div class="grid_12 botspacer60">
Title: <input type="text" name="ud_title" value="<?php echo "$post_title"; ?>">
<br /><br />
News Details:<br />
<textarea id="tiny_mce" name="ud_description" rows="8"><?php echo "$description"; ?></textarea>
I'm not asking to rewrite my code, just a tip or something would be helpful so I can figure out what I did wrong here.
UPDATE This works with some modification to AdRock answer.
<?php
$id = isset($_GET['id']) ? $_GET['id'] : NULL;
$sth = $db->prepare("SELECT `id`, `title`, `description` FROM `htp_news` WHERE `id` = :id");
$sth->bindParam(':id', $id, PDO::PARAM_INT);
$sth->setFetchMode(PDO::FETCH_OBJ);
$sth->execute();
$row = $sth->fetch();
?>
<form method="post" action="update-news.php">
<input type="hidden" name="ud_id" style="width: 100%" value="<?php echo $row->id; ?>">
<div class="grid_12 botspacer60">
Title: <input type="text" name="ud_title" value="<?php echo $row->title; ?>">
<br /><br />
News Details:<br />
<textarea id="tiny_mce" name="ud_description" rows="8"><?php echo $row->description; ?></textarea>
</div>
<div class="grid_12">
<input type="submit" value="Update">
<input type="button" value="Cancel" onclick="window.location = '/admin'">
</div>
</form>
</div>
Here is the action script (update-news.php) that I'm using to add the new data into my database.
<?php
include($_SERVER['DOCUMENT_ROOT'] . "/includes/database.php");
// new data
$id = $_POST['id'];
$title = $_POST['title'];
$description = $_POST['description'];
// query
$sql = "UPDATE `htp_news` SET `title`=?, `description`=? WHERE id=?";
$sth = $db->prepare($sql);
$sth->execute(array($title,$description,$id));
echo "The post has been updated.<br />
<a href='edit-delete-news.php'>Update another position.</a><br />";
?>
Thanks for the help.