我使用php编写了一个小型Web应用程序。我现在正试图用调用存储过程替换我在PHP脚本中直接编写的SQL。
实施例
我已经取代:
$GetIDforInsertSQL=("SELECT idUser FROM user WHERE userName='$username'");
使用:
$GetIDforInsertSQL="CALL Get_User_ID('$username')";
以下是Get_User_ID
的代码CREATE DEFINER=`root`@`localhost` PROCEDURE `Get_User_ID`(IN UserNametoCheck varchar(45) )
BEGIN
SELECT idUser FROM user
WHERE userName=UserNametoCheck;
END
当我运行此查询并提取结果集,即。
$result=($conn->query($GetIDforInsertSQL));
while($row=mysqli_fetch_array($result))// Get the Userid from the users table to insert into watchlist
{
$Userid=$row['idUser'];
echo $Userid;
}
它回显了$ Userid的预期值,即8。
然而,在我的脚本中,我还有另一个查询
$AddToWatchlistSQL=("INSERT INTO watchlist(UserID,AdvertID)VALUES('$Userid','$Advertid')");
接下来是:
$results=($conn->query($AddToWatchlistSQL));
if($results)
{
echo" Advert Added to watchlist, Redirecting";
header('Refresh: 3; "Indexlogged.php');
}
else
{
echo "Thats an error";
}
由于我已经替换了Select状态以使用存储过程Get_User_ID获取userId,因此我不断收到插入查询的错误消息。
当我注释掉存储过程调用并只使用原始查询时:
$GetIDforInsertSQL=("SELECT idUser FROM user WHERE userName='$username'");
它有效,我不明白为什么当我在存储过程调用后回显$ Userid的值时,它会输出预期的结果。关于为什么会发生这种情况的任何想法?
编辑:尝试使用存储过程插入后输出日志文件:
160421 18:35:30 9 Connect root@localhost as anonymous on carhubdb
9 Query SELECT * FROM caradvert WHERE Advert_ID='13'
9 Query SELECT * FROM user WHERE userName='John123'
9 Query SELECT AdvertImagePath FROM advertimage WHERE Advert_IDENTIFIER='13'
9 Query SELECT userName FROM user WHERE idUser='9'
9 Query SELECT * FROM watchlist WHERE UserID='8' AND AdvertID='13'
9 Quit
160421 18:35:32 10 Connect root@localhost as anonymous on carhubdb
10 Query CALL `carhubdb`.`Get_UserID`('John123')