code_junkie

PHP/MySQL update a news record in a database problem

Nov 11th, 2011
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. <?php
  2. $title = "Edit News";
  3. include("../includes/header.php");
  4. include("../includes/database.php");
  5. $done = false;
  6. $expected = array('newstitle', 'newscontent', 'id');
  7. if ($_GET && !$_POST) {
  8. if (isset($_GET['id']) && is_numeric($_GET['id'])) {
  9. $id = $_GET['id'];
  10. }
  11. else {
  12. $id = NULL;
  13. }
  14. if ($id) {
  15. $sql = "SELECT * FROM news WHERE id = $id";
  16. $result = mysql_query($sql) or die ("Error connecting to database...");
  17. $row = mysql_fetch_assoc($result);
  18. }
  19. // if form has been submitted, update record
  20. if (array_key_exists('update', $_POST)) {
  21. // prepare expected items for insertion into database
  22. foreach ($_POST as $key => $value) {
  23. if (in_array($key, $expected)) {
  24. ${$key} = mysql_real_escape_string($value);
  25. }
  26. }
  27. // abandon the process if primary key invalid
  28. if (!is_numeric($id)) {
  29. die('Invalid request');
  30. }
  31. // prepare the SQL query
  32. $query = "UPDATE news SET title = '$title', content = '$content' WHERE id = $id";
  33. // submit the query
  34. $done = mysql_query($query) or die("Error connecting to database...");
  35. }
  36. }
  37. // redirect page if $id is invalid
  38. if ($done) {
  39. header("Location: $ROOT/admin/listnews.php");
  40. exit;
  41. }
  42. ?>
  43.  
  44. if ($_GET && !$_POST) {
  45.  
  46. if (array_key_exists('update', $_POST)) {
  47.  
  48. // prepare the SQL query
  49. $query = "UPDATE news SET title = '$newstitle', content = '$newscontent' WHERE id = $id";
  50.  
  51. if (array_key_exists('update', $_POST)) {
  52.  
  53. if (array_key_exists('update', $_POST)) {
  54. ...
  55. }
  56.  
  57. if (count($_POST) && array_key_exists('update', $_POST)) {
  58. ...
  59. }
Add Comment
Please, Sign In to add comment