php 如何在 CodeIgniter 中测试我的 MySQL 更新查询是否成功?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9913796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:55:00  来源:igfitidea点击:

How do I test if my MySQL update query was successful in CodeIgniter?

phpmysqlcodeigniter

提问by John Hoffman

I have a model function that updates a user in my CodeIgniter application:

我有一个模型函数来更新我的 CodeIgniter 应用程序中的用户:

// updates first of a user, return true if successful, false if not.
public function updateFirstName($userId, $newFirstName) {
    $this->db->query("UPDATE users SET firstName='$newFirstName' WHERE id=$userId");
    return // whether request was successful?
}

How do I return a boolean value that ensures the user of ID $userIdhas been updated? For instance, it should return false if no user was found with ID $userId.

如何返回一个布尔值以确保 ID 的用户$userId已更新?例如,如果没有找到具有 ID 的用户,它应该返回 false $userId

回答by ChrisK

As commented, have you tried $this->db->affected_rows()?

正如评论,你试过$this->db->affected_rows()吗?

That will tell you how many rows were updated.

这将告诉您更新了多少行。

回答by safarov

Check this for more information. Active Records

检查这个以获取更多信息。活动记录

public function updateFirstName($userId, $newFirstName) {

   return $this->db
               ->where('id', $userId)
               ->update("users", array('firstName' => $newFirstName));
}

With this way you will also avoid sql injection that you had before

通过这种方式,您还可以避免之前的 sql 注入

回答by Andre Dublin

if ($this->db->affected_rows() > 0)
{
  return TRUE;
}
else
{
  return FALSE;
}

or

或者

if ($this->db->affected_rows() > 0)
  return TRUE;
else
  return FALSE;

or

或者

return ($this->db->affected_rows() > 0) ? TRUE : FALSE; 

EDIT

编辑

also(much better)

也(好多了)

return ($this->db->affected_rows() > 0);

回答by Berto

A better solution I've found is to manage the difference between an ERROR and 0 affected rows. 0 affected rows is not necessarily a bad thing, but an error is something you do want to know about:

我发现的一个更好的解决方案是管理 ERROR 和 0 个受影响行之间的差异。0 受影响的行不一定是坏事,但错误是您确实想知道的:

if ($this->db->_error_message()) {
    return FALSE; // Or do whatever you gotta do here to raise an error
} else {
    return $this->db->affected_rows();
}

Now your function can differentiate...

现在您的函数可以区分...

if ($result === FALSE) {
    $this->errors[] = 'ERROR: Did not update, some error occurred.';
} else if ($result == 0) {
    $this->oks[] = 'No error, but no rows were updated.';
} else {
    $this->oks[] = 'Updated the rows.';
}

Just some quick hacking there - you should obviously make the code far more verbose if you have other people using it.

只是在那里进行一些快速黑客攻击 - 如果您有其他人使用它,您显然应该使代码更加冗长。

The point is, consider using _error_message to differentiate between 0 updated rows and a real problem.

关键是,考虑使用 _error_message 来区分 0 个更新的行和一个真正的问题。

回答by Devendra Verma

You can use $this->db->affected_rows()in Codeigniter this returns a numeric value when doing "write" type queries (insert, update, etc.).

您可以$this->db->affected_rows()在 Codeigniter中使用它在执行“写入”类型查询(插入、更新等)时返回一个数值。

In MySQL DELETE FROM TABLEreturns 0 affected rows. The database class has a small hack that allows it to return the correct number of affected rows. By default this hack is enabled but it can be turned off in the database driver file. (From CI user guide). For deleted row in Ci it returns 1.

在 MySQL 中DELETE FROM TABLE返回 0 个受影响的行。数据库类有一个小技巧,允许它返回正确数量的受影响行。默认情况下,此 hack 已启用,但可以在数据库驱动程序文件中将其关闭。(来自 CI 用户指南)。对于 Ci 中已删除的行,它返回 1。

回答by Devendra Verma

I have use this code for checking update query.

我已使用此代码检查更新查询。

$status = $this->db->query("UPDATE users SET firstName='$newFirstName' WHERE id=$userId"); 
if($status)
   return true;
else
    return false;

回答by Code Prank

You may use $this->db->affected_rows();to check whether query runs successfully or not

您可以$this->db->affected_rows();用来检查查询是否成功运行

回答by ??ng Hoàng Nguy?n

Use a stored procedure, you can check the result.

使用存储过程,可以检查结果。

Below is a stored procedure example :

下面是一个存储过程示例:

CREATE DEFINER=`root`@`localhost` PROCEDURE `usp_UpdateInfo`(tableId int,tableName varchar(100) charset utf8,description varchar(400) charset utf8)

BEGIN

    declare exit handler for sqlexception select 0 as `result`;

    update table
    set `name` = tableName,
        description = description
    where id = tableId;
    select 1 as `result` ;
END

PHP example code :

PHP 示例代码:

$this->load->database();

$rs = $this->db->query('call usp_UpdateInfo(?,?,?)',array($tableId,$tableName,$description));
$this->db->close();     
return $rs->result_array();

回答by Rafik Bari

public function updateInfo($newinfo) {
    $this->db->update("some_table", $newinfo);
    return ($this->db->affected_rows() > 0);
}

This will either return true or false

这将返回 true 或 false

回答by Null Undefined

Try this:

尝试这个:

public function updateFirstName($userId, $newFirstName) {
    $this->db->where('id', $userId);
    $this->db->set('firstName', $newFirstName);
    $sql = $this->db->update('users');

    if ($sql) { return TRUE; }  // $sql - boolean true or false
}