问题
function stationcost($station1,$station2)
{
$data = array();
$this->db->select('Zone')->from('station_zone')->where('Station', $station1);
$Q = $this->db->get();
$this->db->select('cost')->from('zone_cost')->where('zone', $Q);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$data = $row->Cost;
return $data;
}
}
}
If i change $Q to an integer, the function works correctly. I'm yet to add another station to minus the difference to calculate the zone difference
Convert names to zones $station2 - $station1 = 'calculatedfigure'
Then select cost from zone_cost where zone = 'calculcated figure';
My error message:
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3
SELECT `cost` FROM (`zone_cost`) WHERE `zone` =
Filename: models/station_model.php
Line Number: 59
I've tried this
$this->db->select('Zone')->from('station_zone')->where('Station', $station2);
$S2 = $this->db->get();
$this->db->select('Zone')->from('station_zone')->where('Station', $station1);
$S1 = $this->db->get();
$Q = $S2 - $S1;
回答1:
The problem is that the variable $Q
does not contain a valid value, presumably because the value passed in $station1
does not exist in the database. I would have thought that CI would counter this by at least using an empty quoted string, but apparently not.
You need to validate that $Q
holds a sensible value before you pass it to where()
. For example, another num_rows()
check will tell you whether the first query found anything.
Also, you need to pass the field data from $Q
, not just the object. So in your case, $Q->row()->Zone
.
回答2:
$Q
is an object which has some fields, at this case only one field: Zone
. Please check CodeIgniter Query results
来源:https://stackoverflow.com/questions/8839626/mysql-syntax-error-codeigniter-function-to-calculate-cost