• Resolved grincho

    (@grincho)


    Hello again,

    Scenery: I want to copy data from “wp_users” to another table “user”.
    SQL
    INSERT INTO user(wpUserId, email) SELECT ID, user_email FROM {$wpdb->users} GROUP BY ID;
    woulde be sooo easy. So it’s software development and it’s never “easy” and wpdb has query and insert.

    query combined with prepare reports an error, it’s about quoting.

    $results = $wpdb->get_results(
    			$wpdb->prepare(
    			"
    			INSERT INTO %s ( 'wpUserId', 'email' )
    			SELECT ID, user_email FROM {$wpdb->users} GROUP BY ID;
    			", $tabname
    			)
    	);

    For the insert I have to split the sql up. So started to get the info

    $results = $wpdb->get_results(
    			"
    			SELECT ID as wpUserId, user_email as email FROM {$wpdb->users} GROUP BY ID;
    			", ARRAY_A
    );

    which results in

    Array
    	(
    	    [0] => Array
    	        (
    	            [wpUserId] => 1
    	            [email] => test@mail.com
    	        )
    
    	    [1] => Array
    	        (
    	            [wpUserId] => 2
    	            [email] => anothertest@mail.com
    	        )
    	)

    How to transform that in a key => value array for the insert?
    Or is there an easier way which I overlooked?

Viewing 4 replies - 1 through 4 (of 4 total)
  • Thread Starter grincho

    (@grincho)

    Solved the problem with

    $wpdb->query(INSERT INTO user(wpUserId, email) SELECT ID, user_email FROM {$wpdb->users} GROUP BY ID;)

    Yeah I think this is not a really safe way doing it but I am short on time. Maybe someone has a hint.

    Your SQL is ahead of my skills.
    If I were doing it I would have split the process into two SQL operations like this, (please excuse the sloppy syntax):

    $result = SELECT ID, user_email FROM {$wpdb->users} GROUP BY ID;
    $nrows = 0;
    $upd = ”;
    foreach( result as row) {
    if( 0 == $nrows++ ) $upd .= ‘,’;
    $upd .= $wpdb->prepare(‘(%d,”%s”)’, $row[‘ID’], $row[‘user_email’]);
    }
    if( $nrows) $wpdb->query(‘INSERT INTO ‘.$tabname.’ (wpUserId, email) VALUES ‘.$upd.’;’);

    Thread Starter grincho

    (@grincho)

    Hi Ross,

    I am real sorry for the late answer, a lot of work atm.
    A BIG thanks for your reply, I will check it out later when I fix the update function for the editable grid. Your solution will come in handy, looks safer as mine.

    Later.

    Thread Starter grincho

    (@grincho)

    Hi Ross,

    used your example for updating the table. Thanks to you I have a better solution.

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘Copy data into table / multidimensional array’ is closed to new replies.