I have stored procedure that I created in MySQL and want PHP to call that stored procedure. What is the best way to do this?
-MySQL client version: 4.1.11
-MySQL Server version: 5.0.45
Here is my stored procedure:
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 ;
What is the PHP code to invoke the procedure getTreeNodeName?
To call a stored procedure from a PHP application, you prepare and execute an SQL CALL statement. The procedure that you call can include input parameters (IN), output parameters (OUT), and input and output parameters (INOUT).
A Stored Procedures is a precompiled SQL statement stored in the database for later use. Within a Stored Procedure you can write procedural code that controls the flow of execution. That includes if or else constructs, and error-handling code.
Instead of having PHP code in db you could have just a class name that has method called, say, execute() . Whenever you need to run your custom PHP code just instantiate the class of name you just fetched from db and run ->execute() on it.
It is quite possible that a MySQL stored procedure can call another MySQL stored procedure inside it. To demonstrate it, we are taking an example in which a stored procedure will call another stored procedure to find out the last_insert_id.
I now found solution by using mysqli
instead of mysql
.
<?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 store proc $result = mysqli_query($connection, "CALL StoreProcName"); //loop the result set while ($row = mysqli_fetch_array($result)){ echo $row[0] . " - " . + $row[1]; }
I found that many people seem to have a problem with using mysql_connect, mysql_query and mysql_fetch_array
.
You can call a stored procedure using the following syntax:
$result = mysql_query('CALL getNodeChildren(2)');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With