Guest User

Untitled

a guest
Mar 16th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. <?php
  2.  
  3. $pg_config = 'host=localhost dbname=dbname user=user password=password';
  4.  
  5. $dbh = pg_connect( $pg_config );
  6.  
  7. function import ( $arg_polls_struct ) {
  8.  
  9. global $dbh;
  10.  
  11. foreach( $arg_polls_struct as $poll_info ){
  12.  
  13. // Check to see if user exists
  14. $user_name = pg_escape_string( $poll_info['user_name'] );
  15. $user_email = pg_escape_string( $poll_info['user_email'] );
  16. $query_string = <<<EOF
  17. SELECT user_id FROM users WHERE user_name = '$user_name'
  18. EOF;
  19. $result = pg_query( $dbh, $query_string );
  20.  
  21. if( $row = pg_fetch_assoc( $result ) ){
  22. $poll_info['user_id'] = $row['user_id'];
  23. // Otherwise insert it
  24. } else {
  25. $poll_info['user_id'] = fetch_next_id( 'users_user_id_seq' );
  26. $query_string = <<<EOF
  27. INSERT INTO users ( user_id, user_name, user_email )
  28. VALUES
  29. ( {$poll_info['user_id']}, '$user_name', '$user_email' )
  30. EOF;
  31. $result = pg_query( $dbh, $query_string );
  32. }
  33.  
  34. // Insert poll
  35. $question = pg_escape_string( $poll_info['question_string'] );
  36. $poll_info['poll_id'] = fetch_next_id( 'poll_poll_id_seq' );
  37. $query_string = <<<EOF
  38. INSERT INTO poll ( poll_id, user_id, poll_question )
  39. VALUES
  40. ( {$poll_info['poll_id']}, '{$poll_info['user_id']}', '$question' )
  41. EOF;
  42. $result = pg_query( $dbh, $query_string );
  43.  
  44. // Insert options
  45. foreach( $poll_info['options'] as $poll_option_info ){
  46. $option_num = pg_escape_string( $poll_option_info['option_num'] );
  47. $option_string = pg_escape_string( $poll_option_info['option_string'] );
  48. $option_votes = pg_escape_string( $poll_option_info['option_votes'] );
  49. $option_votes = is_numeric( $option_votes ) ? $option_votes : 0;
  50. $query_string = <<<EOF
  51. INSERT INTO poll_option ( poll_id, poll_option_num, poll_option_string, poll_option_votes )
  52. VALUES
  53. ( {$poll_info['poll_id']}, '$option_num', '$option_string', '$option_votes' )
  54. EOF;
  55. $result = pg_query( $dbh, $query_string );
  56. }
  57.  
  58. } // End each poll
  59.  
  60. }
  61.  
  62. // Not relying on RETURNING function found in postgres >= 8.2
  63. function fetch_next_id ( $arg_seq ) {
  64.  
  65. global $dbh;
  66.  
  67. if( $arg_seq ){
  68. $fetch_id_result = pg_query( $dbh, "SELECT nextval('$arg_seq')" );
  69. $fetch_id_row = pg_fetch_row( $fetch_id_result );
  70. if( is_numeric( $fetch_id_row[0] ) ){
  71. return $fetch_id_row[0];
  72. }
  73. }
  74. return false;
  75. }
  76.  
  77. ?>
Add Comment
Please, Sign In to add comment