shazia
shazia

Reputation: 179

db_affected_rows() always returns false

i want to update a table...by executing the query table does get updated but i also get error message.

How can i fix this..if row is updated then get success message otherwise error.

$sql='UPDATE user SET email='.db_input($_POST['email'])
    .' WHERE uname='.db_input($thisuser->getUserName());

if(db_query($sql)&& db_affected_rows()){
    $msg='Profile Updated Successfully';
}else{
    $errors['err']='Error(s) occured. Profile NOT updated';
}

Thanks

function db_query($query, $database="",$conn=""){ global $cfg; if($conn){ /* connection is provided*/ $response=($database)?mysql_db_query($database,$query,$conn):mysql_query($query,$conn); }else{ $response=($database)?mysql_db_query($database,$query):mysql_query($query); }

    if(!$response) { //error reporting
        $alert='['.$query.']'."\n\n".db_error();
        Sys::log(LOG_ALERT,'DB Error #'.db_errno(),$alert,($cfg &&

$cfg->alertONSQLError())); echo $msg; #uncomment during debuging or dev. } return $response; }

function db_affected_rows() { return mysql_affected_rows(); }

Upvotes: 0

Views: 1006

Answers (2)

googletorp
googletorp

Reputation: 33285

You should use drupal's API, properly, instead of calling functions directly, also you should wrap your tables with {} to support table prefixes.

$sql= "UPDATE {user} SET email='%s' WHERE uname='%s';"

if(db_query($sql, $_POST['email'], thisuser->getUserName())&& db_affected_rows()){
  ..
}

Another thing is that if this is done in form, you should you the form API and use the submit validater to run this code. Also Drupal doesn't have a user table but it does have a users to avoid confusion, you might want to rename your custom table. If you want to update a drupal user account, you should do something like this.

function my_form($form_state) {
  $form['email'] = array(
   '#type' => 'textfield',
   '#title' => t('Title'),
   '#description' => t('The title you enter here appears on the page.'),
  );

  return $form;
}

function my_form_validate(&$form, &$form_state) {
  $mail = $form_state['values']['email'];
  // Validate the email, user form_set_error(), to raise error
}

function my_form_submit(&$form, &$form_state) {
  $mail = $form_state['values']['email'];
  global $user;
  $sql= "UPDATE {users} SET mail='%s' WHERE name='%s';"

  if(db_query($sql, $mail, $user->name) && db_affected_rows()) {
    drupal_set_message(t('Update successful'));
  }
  else {
    ..
  }
}

Upvotes: 0

Vladislav Rastrusny
Vladislav Rastrusny

Reputation: 29993

Your snippet looks fine.

But please note, that if you are changing user email address to the same value, SQL query will be executed ok, but due to optimization reasons, the record will not be updated by MySQL and, therefore db_query() will return true, but db_affected_rows() will return false. You need to decide if this is an intended behavior for you.

Upvotes: 1

Related Questions