存储过程返回空结果

时间:2015-03-30 12:57:24

标签: php mysql stored-procedures pdo

以下是我的存储过程:

DELIMITER $$
--
-- Procedures
--
DROP PROCEDURE IF EXISTS `checkLogin`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `checkLogin`(IN `uname` VARCHAR(255), IN `pwd` VARCHAR(255))
BEGIN
    SELECT a.id, a.role_id, b.name FROM userTable as a
    LEFT JOIN roleTable as b on b.id = a.role_id 
    WHERE a.username = uname AND password = pwd;
END$$

DELIMITER ;

以下是我的执行代码:

    $stmt = $this->dbCon->prepare("CALL checkLogin(?, ?)");

    $stmt->bindParam(1, $email, PDO::PARAM_STR, 4000); 
    $stmt->bindParam(2, $password, PDO::PARAM_STR, 4000); 

    // call the stored procedure
    $stmt->execute();

    //var_dump($res);
    $op = ( $stmt ) ? $stmt->fetchAll(PDO::FETCH_ASSOC) : '';

    echo '<pre>'; print_r($op); die;
上面$this->dbCon中的

是我的PDO对象。

当我执行此代码时,我只获得空结果。但是当我通过phpmyadmin运行程序时,它运行正常。

如果我通过命令行执行它,即使它工作正常:

enter image description here

我也试过下面的方法(收到答案),但仍然是不成功的

$stmt = $db->prepare("Call checkLogin(?,?);");
$stmt->execute(array($email,$password));

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (count($rows) == 0)
    echo 'Failed Login!'."\n";
else
    echo 'Logged In...'."\n".print_r($rows,true);

2 个答案:

答案 0 :(得分:3)

你可以尝试某种方法,这是另一种直接在execute方法中传递键值参数的方法,命名占位符应该在程序中传递

$ stmt = $ this-&gt; dbCon-&gt; prepare(&#34; CALL checkLogin(:Email,:Password)&#34;);

$ keyArray = array(&#34; Email&#34; =&gt;&#34; test@test.com",&#34;密码&#34; =&gt;&#34; 123456&#34 );

$ stmt-&GT;执行($ keyArray);

答案 1 :(得分:1)

这似乎对我有用。但我没有使用Bind参数。绑定似乎对我也有用。我还添加了PDO测试。

代码

//-- Test if PDO is loaded properly.
if (extension_loaded ('PDO' )) { 
    echo 'PDO is loaded'."\n";
    if (extension_loaded('pdo_mysql')) 
        echo 'PDO mysql driver is loaded.'."\n"; 
    else 
        echo 'PDO mysql driver is NOT loaded.'."\n";
} else {
    echo 'PDO is NOT loaded!'."\n";
}

//-- Run a test
$email = 'rob@home.net';
$password = 'abc123!@#';

$db = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', 'toor');

$stmt = $db->prepare("Call checkLogin(?,?);");
$stmt->execute(array($email,$password));

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (count($rows) == 0)
    echo 'Failed Login!'."\n";
else
    echo 'Logged In...'."\n".print_r($rows,true);

输出:

PDO is loaded
PDO mysql driver is loaded.
Logged In...
Array
(
    [0] => Array
        (
            [id] => 1
            [role_id] => 1
            [name] => edit
        )

)