Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a MySQL stored procedure from within PHP code?

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?

like image 423
Pheap Avatar asked Oct 19 '10 09:10

Pheap


People also ask

How can I call stored procedure in PHP?

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).

Why we use stored procedure in PHP?

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.

How do I execute PHP that is stored in a MySQL database?

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.

Can we call procedure inside procedure in MySQL?

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.


2 Answers

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.

like image 64
Pheap Avatar answered Oct 21 '22 09:10

Pheap


You can call a stored procedure using the following syntax:

$result = mysql_query('CALL getNodeChildren(2)'); 
like image 37
phpadmin Avatar answered Oct 21 '22 09:10

phpadmin