Simple Database Insert


/ Published in: PHP
Save to your folder(s)

Just a simple php insert script.


Copy this code and paste it in your HTML
  1. <?php
  2. // Connect to the server::
  3. mysql_connect('localhost','jonno','password')
  4. or die('Sorry, an error occurred when connecting to the server.');
  5.  
  6. // Select the database::
  7. mysql_select_db('carl_forum')
  8. or die ('Sorry, an error occurred when select the database.');
  9.  
  10. if(isset($_POST['post']) && !empty($_POST['post_title']) && !empty($_POST['post_body']))
  11. {
  12. // Set up and clean our variables
  13. $title = strip_tags(mysql_real_escape_string($_POST['post_title']));
  14. $body = strip_tags(mysql_real_escape_string($_POST['post_body']));
  15.  
  16. $sql = "INSERT INTO posts VALUES (NULL,'$title','$body')";
  17. if(mysql_query($sql))
  18. {
  19. echo 'Thanks! you have made a post!';
  20. }
  21. else
  22. {
  23. echo 'Damn! it failed to post.' . mysql_error();
  24. }
  25.  
  26.  
  27. }
  28. ?>
  29.  
  30. <html>
  31. <head>
  32. <title>Carl's Forum</title>
  33. </head>
  34.  
  35. <body>
  36.  
  37. <?php
  38. $sql = "SELECT * FROM posts ORDER BY post_id DESC";
  39. $query = mysql_query($sql);
  40. while($row = mysql_fetch_array($query)) :
  41. ?>
  42. <h1><?php echo $row['post_title']; ?></h1>
  43. <p><?php echo $row['post_body']; ?></p>
  44. <?php endwhile; ?>
  45.  
  46. <form method='post' action='#'>
  47. <input type='text' name='post_title' /><br />
  48. <textarea name='post_body' rows='10' cols='50'></textarea><br />
  49. <input type='submit' name='post' value='Post' />
  50. </form>
  51. </body>
  52. </html>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.