How to execute stored procedures using PDO in PHP?

To execute stored procedures using PDO in PHP, you can follow these steps:

  1. Connect to the database using PDO:
$servername = "localhost"; $username = "root"; $password = "password"; $dbname = "your_database"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected to database successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); }
  1. Prepare the stored procedure using the prepare() method of the PDO object:
$procedureName = 'your_stored_procedure_name'; $parameters = [ ':param1' => 'value1', ':param2' => 'value2', // provide parameter values as needed ]; $stmt = $conn->prepare("CALL $procedureName()");
  1. Bind the parameter values (if any) using the bindParam() method:
foreach ($parameters as $parameter => $value) { $stmt->bindParam($parameter, $value); }
  1. Execute the stored procedure using the execute() method:
$stmt->execute();
  1. Fetch the results (if any) using the fetch() or fetchAll() methods:
// Get a single row $result = $stmt->fetch(PDO::FETCH_ASSOC); // Get all rows $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1. Close the database connection:
$conn = null;

Note: Make sure to replace the variables ($servername, $username, $password, $dbname) with your actual database connection details, and also update your_stored_procedure_name and the $parameters array with your stored procedure name and relevant parameter values.