PHP用in参数调用mysql存储过程

时间:2012-05-14 18:48:39

标签: php mysql

我正在使用两个输入参数调用mysql存储过程。这是我的代码:

if (isset($_POST['button1'])) {
    $con = mysql_connect("localhost:3306","root","");
    if (!$con) {     
        echo '<b>Could not connect.</b>';
        die(mysql_error()); // TODO: better error handling
    } else {          
        mysql_select_db("php_database_1", $con);

        $username_v = $_POST['username'];
        $password_v = $_POST['password'];

        $stmt = $dbh->prepare("CALL login(?, ?)");
        $stmt->bindParam(2, $username_v, $password_v, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); 

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

        print "procedure returned $username_v\n";

执行时,我得到:

  

注意:未定义的变量:第52行的E:\ xampp \ htdocs \ php4 \ default.php中的dbh   致命错误:在第52行的E:\ xampp \ htdocs \ php4 \ default.php中调用非对象的成员函数prepare()

我该如何解决这个问题?

感谢。

3 个答案:

答案 0 :(得分:7)

已修改:在看到更多代码后,您尝试将mysql_()函数与PDO混合使用。您不能这样做 - 而是仅使用PDO。这两个API不能一起工作,旧的mysql_*() API根本不支持预准备语句。

您尚未连接到数据库或实例化PDO对象。

$username_v = $_POST['username'];
$password_v = $_POST['password'];
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';

// You must first connect to the database by instantiating a PDO object
try {
    $dbh = new PDO($dsn, 'root', 'root_db_pw');
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

// Then you can prepare a statement and execute it.    
$stmt = $dbh->prepare("CALL login(?, ?)");
// One bindParam() call per parameter
$stmt->bindParam(1, $username_v, PDO::PARAM_STR); 
$stmt->bindParam(2, $password_v, PDO::PARAM_STR); 

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

答案 1 :(得分:0)

尝试了Michaels解决方案以完成另一项任务并且失败了CALL程序,告诉它预期0参数并且得到2,我将为其他具有相同问题的人解决这个问题:

$username_v = $_POST['username'];
$password_v = $_POST['password'];
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';

// You must first connect to the database by instantiating a PDO object
try {
    $dbh = new PDO($dsn, 'root', 'root_db_pw');
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

// Then you can prepare a statement and execute it.    
$stmt = $dbh->prepare("SET @username_v = '$username_v'; SET @password_v = '$password_v';  CALL login()");

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

答案 2 :(得分:0)

如果您想使用不带PDO的IN参数来调用存储过程,那么下面的代码可能会对您有所帮助。

$stmt = $conn->prepare("CALL dataCreation(?)");
mysqli_stmt_bind_param($stmt, "s", $lastDate);
mysqli_stmt_execute($stmt);

希望这会对某人有所帮助。