我应该在sql命令中写什么来从2个表中选择一个id的数据?

时间:2014-01-12 16:49:00

标签: mysql sql codeigniter

我有两个表,一个是tbl_order,另一个是tbl_order_details。我想通过order_id从两个表中选择数据。我在我的模型中编写了以下sql命令。

function select_order_details($order_id){
$sql = "SELECT 
            tbl_order.order_total,
            tbl_order_details.product_name,
            tbl_order.ordered_date,
            tbl_order.order_id
        FROM tbl_order
        INNER JOIN tbl_order_details 
            ON tbl_order.order_id=tbl_order_details.order_id";

$query_result=$this->db->query($sql);
$result=$query_result->result();
return $result;
}

然后我在我的视图文件中运行一个foreach循环。但我从所有order_id得到了这两个表的所有数据。但我想针对一个order_id选择数据,我将作为参数传递。我怎样才能做到这一点?请帮助。感谢

2 个答案:

答案 0 :(得分:0)

您可以添加where并使用codeigniters查询绑定。代码点火器查询绑定将有助于防止SQL注入攻击。

function select_order_details($order_id){
$sql = "SELECT 
        tbl_order.order_total,
        tbl_order_details.product_name,
        tbl_order.ordered_date,
        tbl_order.order_id
    FROM tbl_order
    INNER JOIN tbl_order_details 
        ON tbl_order.order_id=tbl_order_details.order_id
        where tbl_order. id = ?;"

$query_result=$this->db->query($sql, $order_id);
$result=$query_result->result();
return $result;
}

答案 1 :(得分:-2)

WHERE条件添加到要传递给函数的order_id的过滤器中,如下所示:

$sql = "SELECT tbl_order.order_total,tbl_order_details.product_name,tbl_order.ordered_date,tbl_order.order_id
FROM tbl_order
INNER JOIN tbl_order_details ON tbl_order.order_id=tbl_order_details.order_id where tbl_order.order_id='"+$order_id+"'";