Sql,Object vs String / Array

时间:2012-06-25 17:36:10

标签: php sql

为什么这会产生一个物体?

$sql = $this->db->query("
  SELECT 'product_id'
  FROM " . DB_PREFIX . "product_to_category
  WHERE category_id = '" . $this->db->escape($category['category_id']) . "'
");

如何获得字符串/数组呢?

来自Opencart 相关:类stdClass的对象无法转换为字符串

3 个答案:

答案 0 :(得分:2)

假设CodeIgniter:

http://codeigniter.com/user_guide/database/queries.html

$this->db->query();
  

query()函数在“read”类型时返回数据库结果 object   运行查询,您可以使用它来显示结果。

您可以使用result_array

将结果集行作为数组处理

http://codeigniter.com/user_guide/database/results.html

$query = $this->db->query("YOUR QUERY");

foreach ($query->result_array() as $row){
   echo $row['title'];
   echo $row['name'];
   echo $row['body'];
}

答案 1 :(得分:1)

$sql = $this->db->query("
  SELECT 'product_id'
  FROM " . DB_PREFIX . "product_to_category
  WHERE category_id = '" . $this->db->escape($category['category_id']) . "'
");
$rows = $sql->rows; //array of all returned values
$row = $sql->row; //first row

我强烈建议您使用var_dump($sql)来调查哪些公共对象字段对您有用。

*修正语法

答案 2 :(得分:0)

你的查询语法有错误,你把SELECT'product_id'放在那里你不应该有叛逆。

$sql = $this->db->query("
  SELECT 'product_id'
  FROM " . DB_PREFIX . "product_to_category
  WHERE category_id = '" . $this->db->escape($category['category_id']) . "'
");

您需要进行此更改。

$sql = $this->db->query("
  SELECT product_id
  FROM " . DB_PREFIX . "product_to_category
  WHERE category_id = '" . $this->db->escape($category['category_id']) . "'
");