Support » Plugins » Hacks » WPDB Update only the first row

  • Resolved joker1234

    (@joker1234)


    I have this code, and I want to update only the first row found where the times column is equal to 0, but it updates all.

    $dbHost = 'host';
    $dbUser = 'user';
    $dbPass = 'pass';
    $dbName = 'name';
    
    $mydb = new wpdb($dbUser,$dbPass,$dbName,$dbHost);
    
    $table_name = 'users';
    
    $data = array(
    	'username' => 'name'
    );
    
    $where = array( 'times' => 0 );
    
    $format = array( '%s' );
    
    $where_format = array( '%d' );
    
    $mydb->update( $table_name, $data, $where, $format, $where_format );

    How can I achieve this? Thanks.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Well the ‘where’ is

    'times' => 0

    for sure that is not “equal” to 0.

    Thread Starter joker1234

    (@joker1234)

    Now it updates the DB where times is equal to 0, but it updates all rows. I want it to update only the first row where times is equal to 0.

    You can always create a normal MySQL query like this

    $query  = $mydb->prepare( "UPDATE {$table_name} SET username = %s WHERE times = 0 LIMIT 1", 'name' ); // I guess 'name' will be replaced with a variable like $userName!?
    
    $mydb->query( $query );

    The phrase “first row found” is a bit vague, though. First in terms of what?
    You can specify that by inserting an ORDER BY {fieldname} {ASC/DESC} before the LIMIT 1 statement – if approriate.

    Thread Starter joker1234

    (@joker1234)

    Well I meant anyone, but only one, with ‘times’ equals to 0.
    Anyway your reply was perfect, thanks.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘WPDB Update only the first row’ is closed to new replies.