【问题标题】:Kohana set sessions and databaseKohana 设置会话和数据库
【发布时间】:2012-12-03 18:03:46
【问题描述】:

我正在创建一个小型购物车,并将我的产品保存在会话中(无数据库)。我的会话设置产品 ID。但是如何从我的数据库中获取与存储会话中的产品 ID 匹配的正确产品?

代码:

foreach ( (isset($shopcart) && is_array($shopcart) && count($shopcart) > 0) ? $shopcart : array() as $item )
{  
    $this->template->shopcart =  $shopcart;
}

.

<?php if( isset( $shopcart ) ): ?>
            <?php foreach ($shopcart as $item): ?>
             <?php echo $item['id'] ?>
  <?php endforeach ?>
<?php endif; ?>

编辑:

 foreach ( (isset($shopcart) && is_array($shopcart) && count($shopcart) > 0) ? $shopcart : array() as $item )
    {  
        $this->template->shopcart  = DB::select()->where('id', 'IN', $item['id']) ->from('products')->execute();

        //$this->template->shopcart =  $shopcart;
    }

Database_Exception [1064]:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 ''5'' 附近使用正确的语法 [ SELECT * FROM products WHERE id IN '5' ]

编辑 2:

$this->template->shopcart = array();

if (count($shopcart))
{
  $this->template->shopcart = 
    DB::select()
    ->where('id', 'IN', $item)
    ->from('products')
    ->execute();
}

模板:

<?php if( isset( $shopcart ) ): ?>
  <?php foreach ($shopcart as $item): ?>
<?php echo $item['id'] ?> //This is the product id in my saved session but i need to get the name from the database


 <?php endforeach ?>
 <?php endif; ?>

【问题讨论】:

  • 您遇到了什么问题?无法从会话中获取 ID?还是 DB 的产品?

标签: php orm kohana


【解决方案1】:

您使用的是 ORM 还是查询构建器?如果您使用的是 ORM,您可以这样做:

$this->template->shopcart = 
    ORM::factory('products')
    ->where('id', 'IN', $_SESSION['cart'])
    ->find_all();

如果您使用的是查询生成器:

$this->template->shopcart = 
     DB::select()
     ->where('id', 'IN', $_SESSION['cart'])
     ->from('products')
     ->execute();

在您看来,现在像您一样迭代您的$shopcart

使用您的案例,(将其排除在循环之外)

$this->template->shopcart = array();

if (count($shopcart))
{
  $product_ids = array();
  foreach ($shopcart as $item)
  {
     $product_ids[] = $item['id'];
  }
  $this->template->shopcart = 
    DB::select()
    ->where('id', 'IN', $product_ids)
    ->from('products')
    ->execute();
}

【讨论】:

  • @pocesare 谢谢,但给了我这个错误Database_Exception [ 1241 ]: Operand should contain 1 column(s) [ SELECT * FROM products` WHERE id IN (('5', '1', 'thingy')) ]`
  • 查询生成器的当前代码是什么?更新您的问题并将其包含在内
  • 我不知道你的数据库表定义,但是你的&lt;?php echo $item['id'] ?&gt;你应该改成&lt;?php echo $item['name'] ?&gt;
  • $shopcart 变量的内容是什么?是不是像array(array('id' =&gt; 1), array('id' =&gt; 2))?如果是这种情况,您应该将其更改为 array(1, 2) 然后它将“正常工作”
  • @Frenck 只需将新计数添加到以前的值。将相同的项目存储在不同的行中的原因是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
相关资源
最近更新 更多