To execute stored procedures using PDO in PHP, you can follow these steps:
$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();
}
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()");
bindParam()
method:foreach ($parameters as $parameter => $value) {
$stmt->bindParam($parameter, $value);
}
execute()
method:$stmt->execute();
fetch()
or fetchAll()
methods:// Get a single row
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// Get all rows
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$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.