How can stored procedures in PHP MySQL be utilized effectively for handling business logic?
Stored procedures in PHP MySQL can be utilized effectively for handling business logic by encapsulating complex SQL queries and logic into reusable modules that can be called from PHP code. This helps in centralizing the business logic, improving code organization, and enhancing security by preventing SQL injection attacks.
// Example of calling a stored procedure in PHP MySQL
$mysqli = new mysqli("localhost", "username", "password", "database");
// Prepare the stored procedure call
$stmt = $mysqli->prepare("CALL sp_get_user_info(?)");
// Bind parameters and execute the stored procedure
$user_id = 123;
$stmt->bind_param("i", $user_id);
$stmt->execute();
// Fetch results from the stored procedure
$result = $stmt->get_result();
$user_info = $result->fetch_assoc();
// Close the statement and connection
$stmt->close();
$mysqli->close();
// Make use of $user_info in further business logic