1

I am a Laravel Beginner and after weeks learning and trying i need some help now.

I simple want count an number from my Mysql DB Table in PHP.

My code:

SELECT category_id FROM products WHERE category_id IN (1, 2)

I only know how i can make it in PHP not Laravel with Controllers.

Theres an Simple code how i can display the result in my Laravel php page without this? (i know in laravel i dont need this):

<?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 IN (1, 2)";

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

mysqli_close($con);
?>

And in what files i must add some code thats work? Index,controller,web.php / routes? Because for example if i try:

{{$product->name}} 

i get this error: "Undefined variable: product " Must i connect every page with an Controller?

I need some very easy explain for it with example code if possible:) Thanks

1 Answer 1

1

What you can do in Laravel to get the count of a table is

$count = DB::table('categories')->count();

Which will give you the number of rows within the table 'categories'.

You would usually put this in a controller and pass it to a view.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.