gpt4 book ai didi

php - 如何使用PDO传递参数调用存储过程函数

转载 作者:行者123 更新时间:2023-11-29 06:04:01 26 4
gpt4 key购买 nike

我在使用 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);
}
}
?>

最佳答案

参见 php docs例如:

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

$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

关于php - 如何使用PDO传递参数调用存储过程函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42970793/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com