Simple INSERT, UPDATE from form to MySQL DB


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



Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. $link = mysql_connect('localhost','root','');
  4. mysql_select_db('db_name');
  5. mysql_query('SET NAMES UTF8');
  6.  
  7. $id = 0;
  8. $secured = array();
  9. $secured = sanitize( $_POST );
  10. extract($secured);
  11.  
  12. $db_data = array();
  13. if ( isset($_POST['save']) && $id > 0 ) // update
  14. {
  15. foreach ($data as $table => $value)
  16. {
  17. if ( is_array($value) && ! empty($value) )
  18. {
  19. foreach ($value as $k => $v)
  20. {
  21. $db_data[$table][] = "`$k` = '$v'";
  22. }
  23. }
  24. }
  25.  
  26. foreach ($db_data as $table => $values)
  27. {
  28. if ( mysql_fetch_assoc(mysql_query("SELECT modified FROM $table LIMIT 1")) != '' )
  29. $values[] = '`modified` = NOW()';
  30.  
  31. mysql_query("UPDATE $table SET " . implode(',', $values) . " WHERE id = $id LIMIT 1");
  32. }
  33. }
  34. elseif( isset($_POST['save']) ) // insert
  35. {
  36. foreach ($data as $table => $value)
  37. {
  38. if ( is_array($value) && ! empty($value) )
  39. {
  40. foreach ($value as $k => $v)
  41. {
  42. $db_data[$table]['keys'][] = "`$k`";
  43. $db_data[$table]['values'][] = "'$v'";
  44. }
  45. }
  46. }
  47.  
  48. foreach ($db_data as $table => $values)
  49. {
  50. if ( mysql_fetch_assoc(mysql_query("SELECT created FROM $table LIMIT 1")) != '' )
  51. {
  52. array_push($values['keys'], '`created`');
  53. array_push($values['values'], 'NOW()');
  54. }
  55.  
  56. mysql_query("INSERT INTO $table (" . implode(',', $values['keys']) . ") VALUES (" . implode(',', $values['values']) . ")");
  57. $id = mysql_insert_id();
  58. }
  59. }
  60.  
  61. mysql_close($link);
  62.  
  63. ?>
  64.  
  65. <form action="" method="post">
  66. <input type="hidden" name="id" value="<?php echo $id ?>" />
  67. <input type="text" name="data[users][name]" />
  68. <input type="text" name="data[users][email]" />
  69. <input type="text" name="data[users][address]" />
  70. <input type="text" name="data[users][city]" />
  71. <input type="text" name="data[users][zip]" />
  72. <input type="text" name="data[users][web]" />
  73. <input type="submit" name="save" value="Save" />
  74. </form>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.