The row() method (or row_array()) is the most appropriate call for receiving zero or one record from a query resultset. Your script should accommodate the possibility of a null return value from the method call. Null coalescing is the most elegant way to handle that.
return $this->db
->query($yourSql)
->row()
->campaign_id ?? null;
Equivalent syntax:
return $this->db
->query($yourSql)
->row('campaign_id');
The ability to nominate a column name inside of row() to isolate a specific column value from the first result set row has been available in CodeIgniter for as far back as I could find. If there are no qualifying rows or if the passed-in column name doesn't exist in the query result, then null will be returned.
I verified the above with these versions:
For context, CI3.1.11's row() method signature is as follows. While $n is a poor parameter name, it is designed to work with integers and strings to provide granular data access. If a non-numeric value is provided, then a single value will be returned for the nominated column in the first row. If a numeric value is provided, then the whole row with that index will be returned.
/**
* Row
*
* A wrapper method.
*
* @param mixed $n
* @param string $type 'object' or 'array'
* @return mixed
*/
public function row($n = 0, $type = 'object')
{
if ( ! is_numeric($n))
{
// We cache the row data for subsequent uses
is_array($this->row_data) OR $this->row_data = $this->row_array(0);
// array_key_exists() instead of isset() to allow for NULL values
if (empty($this->row_data) OR ! array_key_exists($n, $this->row_data))
{
return NULL;
}
return $this->row_data[$n];
}
if ($type === 'object') return $this->row_object($n);
elseif ($type === 'array') return $this->row_array($n);
return $this->custom_row_object($n, $type);
}