gpt4 book ai didi

php - mySQL 创建未知数量值的 INSERT 存储过程

转载 作者:行者123 更新时间:2023-11-30 01:28:05 26 4
gpt4 key购买 nike

在我的 mySQL 数据库中,我创建了一个 API,用于使用存储过程从外部使用数据库。

我为该任务指定了一个特殊用户,该用户仅具有 EXECUTE 权限 - 以防止 SQL 注入(inject)。

我有一个用户 ID 连接表,我需要创建一个包含未知数量参数的过程 - 该过程应该将他收到的所有 ID 插入表中。

现在我正在使用 PHP 和 mysqli,并且我正在创建自己的查询 - 这是非常不安全的 - 它看起来像这样:

/**
* Add new rows to the invited users tables
* @param $invitingUser string the inviting user facebook's Id
* @param $invitedUsers array the invited users facebook's Id
*/
function addInvitedUsers($invitingUser, $invitedUsers)
{
//check if all the parameters are set
if (isset($invitingUser) && isset($invitedUsers))
{
//create the basic query for insert
$query = "Insert Into Invited_Users (Inviting_id,Invited_Id) Values ";
//for each invited users - add it to the query
foreach($invitedUsers as $invitedUser)
$query . "('$invitingUser','$invitedUser') ";

if ($this->queryDb($query));
echo "added new invited users";
}
//if parameters are not set - message
else
echo "parameters can't be null";
}

我想创建一个程序来赋予我相同的能力..

我确实知道我无法将数组或未定义数量的参数发送到存储过程,但我确信还有其他方法可以在安全模式下实现相同的功能..

最佳答案

没有简单的方法可以向 MySql 存储过程传递和使用多个值。最好的办法是传递一个以逗号分隔的值字符串,然后将其拆分到 SP 中,而 MySql 不提供开箱即用的方法。

话虽如此,我相信您真正需要的是 prepared statements 。它快速且安全。

function addInvitedUsers($invitingUser, $invitedUsers)
{
//check if all the parameters are set
if (isset($invitingUser) && isset($invitedUsers))
{
// create a prepared statement for insert
$query = "INSERT INTO Invited_Users (Inviting_id, Invited_Id) VALUES (?, ?)";
$stmt = $this->prepare($query); // you need to implement prepare method in your class
// bind parameters
$stmt->bind_param("ii", $invitingUser, $invitedUser);
//for each invited user execute insert
foreach($invitedUsers as $invitedUser) {
if ($stmt->execute()) {
echo "added a new invited user";
}
}
}
//if parameters are not set - message
else
echo "parameters can't be null";
}

显然,您可以将插入封装到 sp 中并使用准备好的语句来调用它

CREATE PROCEDURE addInvitedUser(IN invitingUser INT, IN invitedUser INT)
INSERT INTO Invited_Users (Inviting_id, Invited_Id)
VALUES (invitingUser, invitedUser);

然后在你的函数中改变

$query = "INSERT INTO Invited_Users (Inviting_id, Invited_Id) VALUES (?, ?)";

$query = "CALL addInvitedUser (?, ?)";

关于php - mySQL 创建未知数量值的 INSERT 存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17763540/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com