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


PHP Call mysql stored procedure with in parameter

我正在调用一个具有两个输入参数的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";

执行时,我得到:

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

我该如何解决这个问题?

谢谢。

已编辑:在看到更多代码后,您尝试将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();

在尝试了迈克尔斯解决方案以执行另一项任务后,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();

如果你想调用一个没有PDO的IN参数的存储过程,那么下面的代码可能会帮助你。

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

希望这会帮助某人。