Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $pg_config = 'host=localhost dbname=dbname user=user password=password';
- $dbh = pg_connect( $pg_config );
- function import ( $arg_polls_struct ) {
- global $dbh;
- foreach( $arg_polls_struct as $poll_info ){
- // Check to see if user exists
- $user_name = pg_escape_string( $poll_info['user_name'] );
- $user_email = pg_escape_string( $poll_info['user_email'] );
- $query_string = <<<EOF
- SELECT user_id FROM users WHERE user_name = '$user_name'
- EOF;
- $result = pg_query( $dbh, $query_string );
- if( $row = pg_fetch_assoc( $result ) ){
- $poll_info['user_id'] = $row['user_id'];
- // Otherwise insert it
- } else {
- $poll_info['user_id'] = fetch_next_id( 'users_user_id_seq' );
- $query_string = <<<EOF
- INSERT INTO users ( user_id, user_name, user_email )
- VALUES
- ( {$poll_info['user_id']}, '$user_name', '$user_email' )
- EOF;
- $result = pg_query( $dbh, $query_string );
- }
- // Insert poll
- $question = pg_escape_string( $poll_info['question_string'] );
- $poll_info['poll_id'] = fetch_next_id( 'poll_poll_id_seq' );
- $query_string = <<<EOF
- INSERT INTO poll ( poll_id, user_id, poll_question )
- VALUES
- ( {$poll_info['poll_id']}, '{$poll_info['user_id']}', '$question' )
- EOF;
- $result = pg_query( $dbh, $query_string );
- // Insert options
- foreach( $poll_info['options'] as $poll_option_info ){
- $option_num = pg_escape_string( $poll_option_info['option_num'] );
- $option_string = pg_escape_string( $poll_option_info['option_string'] );
- $option_votes = pg_escape_string( $poll_option_info['option_votes'] );
- $option_votes = is_numeric( $option_votes ) ? $option_votes : 0;
- $query_string = <<<EOF
- INSERT INTO poll_option ( poll_id, poll_option_num, poll_option_string, poll_option_votes )
- VALUES
- ( {$poll_info['poll_id']}, '$option_num', '$option_string', '$option_votes' )
- EOF;
- $result = pg_query( $dbh, $query_string );
- }
- } // End each poll
- }
- // Not relying on RETURNING function found in postgres >= 8.2
- function fetch_next_id ( $arg_seq ) {
- global $dbh;
- if( $arg_seq ){
- $fetch_id_result = pg_query( $dbh, "SELECT nextval('$arg_seq')" );
- $fetch_id_row = pg_fetch_row( $fetch_id_result );
- if( is_numeric( $fetch_id_row[0] ) ){
- return $fetch_id_row[0];
- }
- }
- return false;
- }
- ?>
Add Comment
Please, Sign In to add comment