6.7 C
New York
Wednesday, March 22, 2023

What is ‘mysqli_query() expects at least 2 parameters, 1 given’ Error?

The “mysqli_query() expects at least 2 parameters, 1 given” error is encountered when the mysqli_query() method does not receive proper parameters.

This error occurs when we pass only one parameter to the mysqli_query() function, as the mysqli_query function takes two parameter – one database connection and the second is a query string.

Let us get into the details.

Error Code

<?php
// Mysqli database connection
$conn = mysqli_connect("localhost", "root", "", "databasename");

// Check if connection established 
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

// Select data from table table_employee
$resultAll = mysqli_query("SELECT * FROM table_employee");

if(!$resultAll){
	die(mysqli_error($conn));
}

// Check is result set le grater then 0
if (mysqli_num_rows($resultAll) > 0) {
	while($rowCatData = mysqli_fetch_array($resultAll)){
  		echo $rowCatData["employee_name"].'<br>';
	}
}
?>

Error Code

mysqli_query("SELECT * FROM table_employee");

Correct Code

mysqli_query($conn, "SELECT * FROM table_employee");

In the above example, you can see that we are passing only one parameter to the mysqli_query() query function, in the line mysqli_query(“SELECT * FROM table_employee”).

The error is raised here as the mysqli_query() function takes only one parameter that is query string. As we know that the mysqli_query() function is secure, it requires a database connection and a query string to fire the query to the database.

Corect Example:

<?php
// Mysqli database connection
$conn = mysqli_connect("localhost", "root", "", "databasename");

// Check if connection established 
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

// Select data from table table_employee
$resultAll = mysqli_query($conn, "SELECT * FROM table_employee");

if(!$resultAll){
	die(mysqli_error($conn));
}

// Check is result set le grater then 0
if (mysqli_num_rows($resultAll) > 0) {
	while($rowCatData = mysqli_fetch_array($resultAll)){
  		echo $rowCatData["employee_name"].'<br>';
	}
}
?>

Here, it can be observed that the mysqli_query() method takes 2 parameters. So, the error is avoided and the code runs fine.  

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles