Asked 7 years ago
30 Jan 2017
Views 1185
sqltreat

sqltreat posted

how to run MySQL stored procedure in php ?

how to run MySQL stored procedure in php ?


CREATE PROCEDURE getdata(x VARCHAR(5))
BEGIN
  DECLARE name VARCHAR(5) DEFAULT 'bob';
  DECLARE newname VARCHAR(5);
  DECLARE id INT;

  SELECT name , id INTO newname, xid
    FROM table1 WHERE name= name;
  SELECT newname;



how to run this stored procedure in PHP ?
QuickIos

QuickIos
answered Apr 24 '23 00:00

Sure, here's a possible rewritten version:

To execute a MySQL stored procedure in PHP, there are two extensions available to use, which are mysqli and PDO .

Below is an example using mysqli :



// Establish a database connection
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check for connection errors
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: " . $mysqli->connect_error;
    exit();
}

// Prepare the stored procedure call
$stmt = $mysqli->prepare("CALL my_stored_procedure(?, ?)");

// Bind parameters to the stored procedure call
$stmt->bind_param("ss", $param1, $param2);

// Set the parameter values for the stored procedure call
$param1 = "value1";
$param2 = "value2";

// Execute the stored procedure call
$stmt->execute();

// Close the prepared statement
$stmt->close();

// Close the database connection
$mysqli->close();

Alternatively, here's an example using PDO :



// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password");

// Prepare the stored procedure call
$stmt = $pdo->prepare("CALL my_stored_procedure(?, ?)");

// Bind parameters to the stored procedure call
$stmt->bindParam(1, $param1);
$stmt->bindParam(2, $param2);

// Set the parameter values for the stored procedure call
$param1 = "value1";
$param2 = "value2";

// Execute the stored procedure call
$stmt->execute();

// Close the prepared statement
$stmt->closeCursor();

// Close the database connection
$pdo = null;
Post Answer