[英]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.我有在 MySQL 中创建的存储过程,并希望 PHP 调用该存储过程。 What is the best way to do this?做这个的最好方式是什么?
-MySQL client version: 4.1.11 -MySQL客户端版本:4.1.11
-MySQL Server version: 5.0.45 -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 代码是什么?
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
有问题。
您可以使用以下语法调用存储过程:
$result = mysql_query('CALL getNodeChildren(2)');
This is my solution with prepared statements and 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();
<?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;
}
Following code show, how to call store procedure with example 以下代码显示了如何使用示例调用存储过程
$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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.