How to Call a MySQL Stored Procedure from PHP Code
Background:
Calling MySQL stored procedures from PHP code allows you to execute complex database operations effectively. This article demonstrates the best approach for invoking a stored procedure from PHP using MySQL versions 4.1.11 (client) and 5.0.45 (server).
Stored Procedure Definition:
The example stored procedure, getTreeNodeName, returns the name of a node given its ID:
DELIMITER $$ DROP FUNCTION IF EXISTS `getNodeName` $$ CREATE FUNCTION `getTreeNodeName`(`nid` int) RETURNS varchar(25) CHARSET utf8 BEGIN DECLARE nodeName varchar(25); SELECT name into nodeName FROM tree WHERE id = nid; RETURN nodeName; END $$ DELIMITER ;
PHP Code to Invoke Stored Procedure:
To call the getTreeNodeName procedure, you can use the mysqli extension instead of the deprecated mysql extension. Here's the PHP code:
<?php // enable error reporting mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // connect to database $connection = mysqli_connect("hostname", "user", "password", "db", "port"); // run the stored procedure $result = mysqli_query($connection, "CALL getTreeNodeName"); // loop the result set while ($row = mysqli_fetch_array($result)) { echo $row[0] . " - " . $row[1]; // replace with appropriate column indices }
Note:
Many users have reported issues with using the older mysql_connect, mysql_query, and mysql_fetch_array functions. It's recommended to use the mysqli extension instead.
The above is the detailed content of How to Call a MySQL Stored Procedure from PHP Code?. For more information, please follow other related articles on the PHP Chinese website!