How can I solve this?

function Get_total_student()
{
	$stm = $db->prepare("SELECT COUNT(id) as Total FROM students");
	//$stm = $db->prepare("SELECT COUNT(student_id) as Total FROM student_srms WHERE student_status = 'Enable'");
	//$stm->bindParam(":id", $exam, PDO::PARAM_STR);
	$stm->execute();
	$result = $stm->fetch(PDO::FETCH_ASSOC);
	foreach($result as $row)
	{
		return $row["Total"];
	}
}

Notice: Undefined variable: db in C:\xampp\htdocs\rt\function.php on line 108

Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\rt\function.php on line 108

Quite simply, the variable $db needs to be defined.
Bear in mind the scope of variables in PHP. If defined outside of a function, it won’t be defined within the scope of the function.

1 Like

What should I do to remove this line?


Warning: Illegal string offset 'Total' in C:\xampp\htdocs\rt\function.php on line 116
3
function test()
{
  global $db;
  $stm = $db->prepare("SELECT COUNT(id) as Total FROM students");
  //$stm = $db->prepare("SELECT COUNT(student_id) as Total FROM student_srms WHERE student_status = 'Enable'");
  //$stm->bindParam(":id", $exam, PDO::PARAM_STR);
  $stm->execute();
  $result = $stm->fetch(PDO::FETCH_ASSOC);
  foreach($result as $row)
  {
    return $row["Total"];

  }
}

You’re fetching exactly 1 row. Did you mean to fetchAll instead?

Either you fetchAll to pull all the rows, or you dont need the foreach to walk through a single row. (at that point, $result = $row)

1 Like

I forgot that. Thank you.