如何从 PHP 代码中调用 MySQL 存储过程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3966747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call a MySQL stored procedure from within PHP code?
提问by Pheap
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 中创建的存储过程,并希望 PHP 调用该存储过程。做这个的最好方式是什么?
-MySQL client version: 4.1.11
-MySQL Server version: 5.0.45
-MySQL 客户端版本:
4.1.11 -MySQL 服务器版本: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?
调用过程 getTreeNodeName 的 PHP 代码是什么?
回答by Pheap
I now found solution by using mysqli
instead of mysql
.
我现在通过使用mysqli
而不是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
.
我发现很多人似乎在使用mysql_connect, mysql_query and mysql_fetch_array
.
回答by phpadmin
You can call a stored procedure using the following syntax:
您可以使用以下语法调用存储过程:
$result = mysql_query('CALL getNodeChildren(2)');
回答by Zahra
This is my solution with prepared statementsand stored procedure is returning several rows not only one value.
这是我使用准备好的语句和存储过程返回多行而不是一个值的解决方案。
<?php
require 'config.php';
header('Content-type:application/json');
$connection->set_charset('utf8');
$mIds = $_GET['ids'];
$stmt = $connection->prepare("CALL sp_takes_string_returns_table(?)");
$stmt->bind_param("s", $mIds);
$stmt->execute();
$result = $stmt->get_result();
$response = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($response);
$stmt->close();
$connection->close();
回答by Petah
<?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;
}