如何从PHP代码中调用MySQL存储过程?
我有我在MySQL中创build的存储过程,并希望PHP调用该存储过程。 什么是最好的方法来做到这一点?
-MySQL客户端版本:4.1.11
-MySQL服务器版本:5.0.45
这是我的存储过程:
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代码来调用过程getTreeNodeName?
我现在通过使用mysqli
而不是mysql
来find解决scheme。
<?php //connect to database $connection = mysqli_connect("hostname", "user", "password", "db", "port"); //run the store proc $result = mysqli_query($connection, "CALL StoreProcName") or die("Query fail: " . mysqli_error()); //loop the result set while ($row = mysqli_fetch_array($result)){ echo $row[0] . " - " . + $row[1]; } ?>
我发现很多人似乎在使用mysql_connect, mysql_query and mysql_fetch_array
遇到了问题。
您可以使用以下语法调用存储过程:
$result = mysql_query('CALL getNodeChildren(2)');
<?php $res = mysql_query('SELECT getTreeNodeName(1) AS result'); if ($res === false) { echo mysql_errno().': '.mysql_error(); } while ($obj = mysql_fetch_object($res)) { echo $obj->result; }
请参阅从Artful MySQL提示列表中的PHP调用存储过程来调用存储过程
官方的PHP文档也提供了方向
下面的代码显示,如何用示例调用存储过程
$con = mysql_connect('localhost','root',''); mysql_select_db('books'); //Call the proc() procedure follow $result= mysql_query("CALL proc();") or die(mysql_error()); while($row = mysql_fetch_row($result)) { for($i=0;$i<=6;$i++) { echo $row[$i]."<br>"; } } mysql_close($con);
我从php.net得到的解决scheme
<?php $mysqli = new mysqli("localhost", "root", "", "joomla2.5"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; } /*if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)") || !$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)")) { echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error; } if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") || !$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;')) { echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error; } if (!$mysqli->multi_query("CALL p()")) { echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error; } do { if ($res = $mysqli->store_result()) { printf("---\n"); var_dump($res->fetch_all()); $res->free(); } else { if ($mysqli->errno) { echo "Store failed: (" . $mysqli->errno . ") " . $mysqli->error; } } } while ($mysqli->more_results() && $mysqli->next_result());
?>