WordPress.org

Forums

[resolved] WPDB Update only the first row (5 posts)

  1. joker1234
    Member
    Posted 1 year ago #

    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.

  2. tmeister
    Member
    Posted 1 year ago #

    Well the 'where' is

    'times' => 0

    for sure that is not "equal" to 0.

  3. joker1234
    Member
    Posted 1 year ago #

    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.

  4. Chris
    Member
    Posted 1 year ago #

    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.

  5. joker1234
    Member
    Posted 1 year ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags