2017-09-21 74 views
0

我在Laravel 5.5中有一个边栏菜单,我想用更多的ID显示分类计数,但是他们不显示任何结果。Laravel显示类别计数不显示

我的代码:

<?php 
$count = DB::select('select category_id from products where category_id = :id', ['id' => 1]); 
?> 

,我怎么能选择更多的ID's?示例where category_id = 1 and 2

我现在试用了一个多星期,希望有人能帮助我现在在这里。

我的PHP代码的作品,但它不是laravel;)

<?php 
$con=mysqli_connect("host","username","password","database"); 
// Check connection 
if (mysqli_connect_errno()) 
    { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 

$sql="SELECT category_id FROM products WHERE category_id = 2"; 

if ($result=mysqli_query($con,$sql)) 
    { 
    // Return the number of rows in result set 
    $rowcount=mysqli_num_rows($result); 
    printf("Result set has %d rows.\n",$rowcount); 
    // Free result set 
    mysqli_free_result($result); 
    } 

mysqli_close($con); 
?> 
+0

[Rü使用laravel控制器,路线? – RamAnji

+0

是的,我使用控制器,路线 –

+0

你需要在laravel写这个代码? – RamAnji

回答

0

DB::select()返回结果的数组,所以你可以指望的结果:

$count = count(DB::select('select category_id from products where category_id = :id', ['id' => 1])); 

但是,您可能更喜欢使用在query builder and the count() aggregate function

$count = DB::table('products')->whereIn('category_id', [1])->count(); 

这使您可以通过多个category_ids像这样:

$count = DB::table('products')->whereIn('category_id', [1, 2, 3])->count(); 
+0

谢谢,但也没有结果,页面上没有显示...我不知道,我现在试试许多事情,没有工作。 –

+0

你用'echo $ count;'显示计数吗? – MrCode

+0

我是个白痴,不会忘记xD你是我的英雄!很多谢谢它工作正常:) –

0

你可以试试这个

<?php 

$count = DB::select('select category_id from products where category_id = :id', ['id' => 1])[0]['category_id ']; 
echo $count; 

?> 
+0

它出现这个错误:不能使用stdClass类型的对象作为数组 –

+0

你可以在DB.php类中显示我的函数'select' – Tiki