MYSQL Syntax error - Codeigniter function to calculate cost

半腔热情 提交于 2020-01-06 12:55:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!