Posted By

shawntysco on 09/22/10


Tagged

mysql insert php runtime


Versions (?)

PHP, Build a basic dynamic INSERT string


 / Published in: PHP
 

URL: linkdeo.net

Makes basic insert statements a breeze to type while doing basic PHP inserts.\r\n*The function for \\'querys\\' on line 44 can be found here: http://snipplr.com/view/40911/query-the-database-php/ *

  1. //Insert
  2. //$sql = "INSERT INTO quick_links (title, link) VALUES('" . $_POST['title'] . "', '" . $link . "');";
  3. function add($table, $columns, $values){
  4.  
  5. //begin the insert into*******************************************************
  6. $sql = "INSERT INTO " . $table;
  7.  
  8. //iterate through the $table**************************************************
  9.  
  10. //iterate through the $columns ***********************************************
  11. $sql = $sql . " (" . $columns . ") VALUES(";
  12.  
  13. //iterate through the $values*************************************************
  14. $arrValue = explode("|", $values);
  15. //loop the array
  16. foreach($arrValue as $arrValueResult){
  17.  
  18. //check if last index in array
  19. if (end($arrValue) == $arrValueResult){
  20. if((is_numeric($arrValueResult)) || ($arrValueResult == "NOW()")){
  21. $arrValueResult = $arrValueResult ;
  22.  
  23. }else{
  24. $arrValueResult = "'" . $arrValueResult . "'" ;
  25. }
  26. }else{
  27. if((is_numeric($arrValueResult)) || ($arrValueResult == "NOW()")){
  28. $arrValueResult = $arrValueResult . ", " ;
  29. }else{
  30. $arrValueResult = "'" . $arrValueResult . "', " ;
  31. }
  32. }//end if
  33.  
  34. //add to $sql
  35. $sql = $sql . $arrValueResult;
  36. }//end for each
  37.  
  38. //end the $sql
  39. $sql = $sql . ");";
  40.  
  41. //determine is item in $values is an interger / string
  42. //echo $sql;
  43. //insert the query
  44. $insert_sql = querys($sql);
  45. }//end add
  46.  
  47. //-----------------------------------------------------------------
  48. //To use this function:
  49. $add_cat = add("categories", "cat", $_POST['cat']);

Report this snippet  

You need to login to post a comment.