新手求助:CodeIgniter中数据库查询结果加法报错解决
Hey there! Let's fix that error you're seeing. The problem is straightforward: your variables $fromrequest and $fromstock aren't the integer values you expect—they're CodeIgniter database result objects (of type CI_DB_mysqli_result). These objects hold the full result set and metadata from your query, not just the single number you need. You can't directly add them like integers, which is why you're getting that conversion error.
How to fix it
You need to extract the actual sunit value from each result object first. Here's how to do it properly, with safety checks for cases where the query might return no results:
// Get the sunit value from Requests table (with fallback to 0 if no record found) $request_result = $this->db->query("SELECT sunit FROM Requests WHERE sid = 2")->row(); $request_value = $request_result ? (int)$request_result->sunit : 0; // Get the sunit value from Stock table (same safety check) $stock_result = $this->db->query("SELECT sunit FROM Stock WHERE ssid = 5")->row(); $stock_value = $stock_result ? (int)$stock_result->sunit : 0; // Now you can safely add the two integers $sum = $request_value + $stock_value;
What's happening here?
->row()fetches the first (and only, in your case) record from the query result as an object.- The ternary operator (
? :) checks if the result exists—if it does, we castsunitto an integer; if not, we use0to avoid errors from null values. - Finally, we add the two integer values to get your sum.
Alternative: Using array results
If you prefer working with arrays instead of objects, you can use ->row_array() instead:
$request_result = $this->db->query("SELECT sunit FROM Requests WHERE sid = 2")->row_array(); $request_value = isset($request_result['sunit']) ? (int)$request_result['sunit'] : 0; $stock_result = $this->db->query("SELECT sunit FROM Stock WHERE ssid = 5")->row_array(); $stock_value = isset($stock_result['sunit']) ? (int)$stock_result['sunit'] : 0; $sum = $request_value + $stock_value;
Quick (but less safe) one-liner
If you're 100% sure the query will always return a record, you can condense it to a single line—but this will throw an error if no record is found:
$sum = (int)$this->db->query("SELECT sunit FROM Requests WHERE sid = 2")->row()->sunit + (int)$this->db->query("SELECT sunit FROM Stock WHERE ssid = 5")->row()->sunit;
Always prefer the versions with safety checks though—they'll make your code more robust!
内容的提问来源于stack exchange,提问作者Sanyam Negi

