通过Codeigniter从MySQL表中获取数据

时间:2013-07-10 11:13:23

标签: php mysql codeigniter

我在使用codeigniter Controller中获取此数据时遇到问题。

    $q = $this->db->get('offers_orders');
    $this->db->select('total');
    $this->db->where('order_number', $orderid);


    $orderdata = $q->result_array();

    $orderamount = $orderdata[0]['total'];

您认为此代码有什么问题吗?。

3 个答案:

答案 0 :(得分:2)

是的,试试:

$this->db->select('count(*) as total', false);
$this->db->where('order_number', $orderid);
$q = $this->db->get('offers_orders');

OR,

$q = $this->db->select('count(*) as total', false)->where('order_number', $orderid)->get('offers_orders');

答案 1 :(得分:0)

首先需要定义select和where方法,然后调用用于获取数据的get()方法。

像这样:

$this->db->select('total');
$this->db->where('order_number', $orderid);
$q = $this->db->get('offers_orders');

正如我从您的查询中看到的,您只需要获取一个结果,因此更好的解决方案是使用row()函数,因为此函数返回单个结果行。

像这样:

$orderdata = $q->row();
$orderamount = $orderdata->total;

另外,如需了解更多信息,请阅读this acticle

答案 2 :(得分:-1)

 <!DOCTYPE html>
<html>
<body>

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     // output data of each row
     while($row = $result->fetch_assoc()) {
         echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"] . "<br>";
     }
} else {
     echo "0 results";
}

$conn->close();
?> 

</body>
</html>