Updating a table via php mysql
This is my code to update the table. My problem is that after submitting a new entry, I cannot update it the first time (it shows blank), but the second time it works fine.
One more thing, when I remove the include statement, it works fine on submessage.php, there is no phpcode. [annakata: I have no idea what that means]
$pid = $_GET['id'];
$title = $_POST['title'];
$summary = $_POST['summary'];
$content = $_POST['content'];
$catid = $_POST['cid'];
$author = $_POST['author'];
$keyword = $_POST['keyword'];
$result1= mysql_query("update listing set catid='$catid',title='$title',
summary='$summary',content='$content', author='$author', keyword='$keyword' where pid='$pid'",$db);
include("submessage.php");
What's wrong with this piece of code is hard to list. However, at least you must establish a database connection before you can request one.
a source to share
Why not just redirect to submessage.php
rather than insert it? The redirection also prevents duplicate db operations when the user refreshes the page. Just replace the operator include
with:
header('Location: submessage.php?id=' . $pid);
die();
Also, before deploying the application: DO NOT USE THE USER LOGIN DIRECTLY IN SQL QUERY . You should use bound parameters instead. If not, you might as well publicly advertise your database administrator password. More about PDO and prepared reports http://ie.php.net/pdo
This is how I would do it:
$pdo = new PDO(....); // some configuration parameters needed
$sql = "
UPDATE listing SET
catid=:catid, title=:title, summary=:summary,
content=:content, author=:author, keyword=:keyword
WHERE pid=:pid
";
$stmt = $pdo->prepare($sql);
$stmt->bindValue('catid', $_POST['catid']);
$stmt->bindValue('title', $_POST['title']);
$stmt->bindValue('summary', $_POST['summary']);
$stmt->bindValue('content', $_POST['content']);
$stmt->bindValue('author', $_POST['author']);
$stmt->bindValue('keyword', $_POST['keyword']);
$stmt->bindValue('pid', $pid = $_GET['id']);
$stmt->execute();
header('Location: submessage.php?id=' . $pid);
die();
Or, actually, I would use some ORM solution to make it look more similar:
$listing = Listing::getById($pid = $_GET['id']);
$listing->populate($_POST);
$listing->save();
header('Location: submessage.php?id=' . $pid);
die();
a source to share
Aside from the usual SQL injection warnings - it is very likely that your code is and where you are getting the query parameters (without any validation) - then it is very possible that your problem has nothing to do with the queries, in particular if it is working on subsequent attempts. Are you sure $ _GET ['id'] is set the first time the script is called?
Just to point out that there is absolutely no reason to run multiple update requests for each field that needs to be updated - just combine them into one request.
a source to share