如何通过使用PDO传递参数来调用存储过程函数

时间:2017-03-23 08:32:55

标签: php mysql pdo

我在使用PDO调用存储过程时遇到问题。我在一个类中有一个PDO配置,我必须从myfile.php传递一个参数,即用户输入号。我已在下面上传了我的文件。

myfile.php

include 'database.php';
$test = new Database();
$test->query('CALL calcArea(?)');
$test->bind(':s_id', $s_id);
$rslt= $test->execute();

print_r($rslt);

database.php

<?php
    class Database{
        private $host = DB_HOST;
        private $user = DB_USER;
        private $pass = DB_PASS;
        private $dbname = DB_NAME;

        private $conn;
        private $error;
        private $stmt;

        public function __construct(){
            // Set DSN
            $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
            // Set options
            $options = array(
                PDO::ATTR_PERSISTENT    => true,
                PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
                );
            // Create a new PDO instanace
            try{
                $this->conn = new PDO($dsn, $this->user, $this->pass, $options);
            }
            // Catch any errors
            catch(PDOException $e){
                $this->error = $e->getMessage();
            }
        }

        public function query($sql){
            $this->stmt = $this->conn->prepare($sql);
        }

        public function bind($param, $value, $type = null){
            if (is_null($type)) {
                switch (true) {
                    case is_int($value):
                    $type = PDO::PARAM_INT;
                    break;
                    case is_bool($value):
                    $type = PDO::PARAM_BOOL;
                    break;
                    case is_null($value):
                    $type = PDO::PARAM_NULL;
                    break;
                    default:
                    $type = PDO::PARAM_STR;
                }
            }
            $this->stmt->bindValue($param, $value, $type);
        }
    }
    ?>

1 个答案:

答案 0 :(得分:2)

有关示例,请参阅php docs

$stmt = $dbh->prepare("CALL calcArea(?)");
$stmt ->execute(array($s_id));

OR

$stmt = $dbh->prepare("CALL calcArea(?)");
$stmt->bindParam(1, $s_id, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT, 32)
$stmt->execute();
var_dump($value);//<- result is now in $value