简体   繁体   中英

Get 'Update' error using SQLite3 and PHP

I created a function that tries to UPDATE a value using a condition. If something goes wrong, it tries to do a INSERT.

The code is as follow:

if(!$result=$this->query("UPDATE collect_data_settings SET setting_value ='".$setting_value."' WHERE collect_point = '".$collect_point."' AND setting_name='".$setting_name."';"))
        $result=$this->query("INSERT INTO collect_data_settings ('collect_point','setting_name','setting_value') VALUES ('".$collect_point."','".$setting_name."','".$setting_value."');");

Unfortunately, for some reason the UPDATE query never returns false even if the condition is not satisfied. Can someone help me?

Why don't you try doing a search for the collect_point (assuming this is a unique key) variable first and if it is not yet in the database you use the INSERT statement and if not you use the UPDATE statement. For example:

$db = new SQLite3('database.db')    
$check = $db->query("SELECT * FROM collect_data_settings WHERE collect_point = '$collect_point'")
$check_query = $check->numRows();

if($check_query > 0) {
    *Your UPDATE query*
}else {
    *Your INSERT query*
}

The UPDATE statement modifies all rows that happen to match the WHERE condition. The final number does not matter; even if no row matches, all rows were checked successfully.

To find out how many rows were changed, use the changes() function :

$this->exec("UPDATE ... WHERE ...");
if ($this->changes() == 0)
    $this->exec("INSERT ...");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM