Select query with bind and prepare in Prepared Statements

In order to execute Select statements through prepared statements we have to first bind input parameters with bind_param and then for storing results bind_result is used where :

bind_param Binds variables to a prepared statement as parameters
bind_result Binds variables to a prepared statement for result storage

Example

$UserNameOrEmail = $_POST["userName"];
$PasswordForAdmin = $_POST["password"];

if($stmt = $mysqli->prepare("SELECT Id, userName, email, mobileNumber FROM users WHERE email LIKE ? and password LIKE ? LIMIT 1")) {
	
	// binding parameters of query with form post parameters
	$stmt->bind_param("ss", $UserNameOrEmail, $PasswordForAdmin);
	
	// executing query
	$stmt->execute();
	
	// binding result of the query with some dummy variables
	$stmt->bind_result($idOfUser, $userName, $emailOfUser, $mobileNumberOfUser);
	
	while ($stmt->fetch()) {
		echo $idOfUser;
		echo $userName;
		echo $emailOfUser;
		echo $mobileNumberOfUser;
	}

	$stmt->close();

	/* close connection */
	$mysqli->close();
}
else 
{
	echo "Invalid Credentials";
}
Share

You may also like...