存储过程的替代方案
我在使用存储过程时遇到问题。调用存储过程对我来说不起作用。所以我用sql语句替换了存储过程。但现在,我有一些接收参数的存储过程。例如,
CREATE PROCEDURE get_category_details_proc(IN incat_id INT)
BEGIN
SELECT name, desc
FROM category
WHERE cat_id = incat_id;
END
我如何通过简单的 sql 语句来替换它?
请参阅我之前的问题了解更多详细信息。
我的数据库连接类中已经有这个函数:
public static function GetRow($sqlQuery, $params = null, $fetchStyle = PDO::FETCH_ASSOC)
{
$result = null;
try
{
$database_handler = self::GetHandler();
$statement_handler = $database_handler->prepare($sqlQuery);
$statement_handler->execute($params);
$result = $statement_handler->fetch($fetchStyle);
}
catch(PDOException $e)
{
self::Close();
trigger_error($e->getMessage(), E_USER_ERROR);
}
return $result;
}
在另一个类中,我实际上调用了我拥有的存储过程:
public static function GetCategoryDetails($categoryID)
{
$sql = CALL get_category_details_proc(:category_id);
$params = array(':category_id' => $categoryID);
return DatabaseHandler::GetRow($sql,$params);
}
I am having problems using stored procedures. Making call to a stored procedure is not working for me. So I replaced the stored procedure by an sql statement. But now, I have some stored procedures which receive parameters. for example
CREATE PROCEDURE get_category_details_proc(IN incat_id INT)
BEGIN
SELECT name, desc
FROM category
WHERE cat_id = incat_id;
END
How can I replace this by using simply sql statements?
Please see my previous question for more details.
I already have this function in my database connection class:
public static function GetRow($sqlQuery, $params = null, $fetchStyle = PDO::FETCH_ASSOC)
{
$result = null;
try
{
$database_handler = self::GetHandler();
$statement_handler = $database_handler->prepare($sqlQuery);
$statement_handler->execute($params);
$result = $statement_handler->fetch($fetchStyle);
}
catch(PDOException $e)
{
self::Close();
trigger_error($e->getMessage(), E_USER_ERROR);
}
return $result;
}
And in another class where I am actually calling the stored procedures I have:
public static function GetCategoryDetails($categoryID)
{
$sql = CALL get_category_details_proc(:category_id);
$params = array(':category_id' => $categoryID);
return DatabaseHandler::GetRow($sql,$params);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用如下所示的准备好的语句:
Use a Prepared statement like the following:
您可以仅使用串联来构建查询字符串,但正如 Rick 在下面提到的那样,请确保强制转换/验证。始终清理所有外部输入 - 使用 mysql_real_escape_string,或者更好的是,准备好的语句
然后将其传递到 PHP mysql_query
You could just build the query string with concatenation but as Rick mentions below make sure to cast/validate. Always sanitize all external inputs - use mysql_real_escape_string, or better still, prepared statements
Then pass that into the PHP mysql_query