编程语言
首页 > 编程语言> > php-pdo定义一个函数,然后在select语句中使用它

php-pdo定义一个函数,然后在select语句中使用它

作者:互联网

我的查询有点像这样:

CREATE FUNCTION func ... ;
SELECT * FROM  ....;

我使用的是php的PDO,在$pdo-> query()中不允许使用超过1条语句,所以我决定将查询分为两部分,因此我使用$pdo执行CREATE FUNCTION查询-> exec(),然后在select语句上使用$pdo-> query().

但是,我在执行select语句时收到错误消息,即FUNCTION database.func不存在.我该如何解决?当我在phpmyadmin中将其作为单个查询运行时,它工作正常

编辑:PHP代码:

class MyClass {
function connectPDO($user,$pass,$chartset="utf8"){
    //simple function for making a new PDO object and mysql connection
    $dbname = "my_db";
    try {
        //creating new pdo
        $pdo = new PDO('mysql:host=localhost;dbname='.$dbname, $user,$pass);
        //attributes set to throw errors and exceptions which can be caught, can be changed
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        //fetch associative arrays
        $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
        //default chartset
        $pdo->exec('SET NAMES "'.$chartset.'"');
      } catch (PDOException $e) {
        //on some error
        $output = "Ay caramba! there's something wrong here!.<br>";
        echo $output.$e->getMessage();
        exit();
    }

    $this->db = $pdo;
}
}

$object = new MyClass();
$object->connectPDO("user","pass");
$sqlPreliminary = "
        DROP FUNCTION IF EXISTS myFunc;
        DELIMITER //

        CREATE FUNCTION myFunc (id INT)
            RETURNS DECIMAL

            BEGIN
            RETURN id + 1;
            END //
        DELIMITER ;

";

$sqlFinal = "
    SELECT id, myFunc(id) AS plusOne  FROM table;
";
$object->db->exec($sqlPreliminary);
var_dump($object->db->query($sqlFinal)->fetchAll(PDO::FETCH_ASSOC));

解决方法:

使用PDO创建用户定义的函数仅由exec起作用,不需要定界符. $db是PDO实例.

$db->exec('CREATE FUNCTION ConvertHTMLToText(str LONGTEXT CHARSET utf8)
           RETURNS LONGTEXT CHARSET utf8
           BEGIN
           DECLARE start, end INT DEFAULT 1;
           LOOP
           SET start = LOCATE("<", str, start);
           IF (!start) THEN RETURN str; END IF;
           SET end = LOCATE(">", str, start);
           IF (!end) THEN SET end = start; END IF;
           SET str = TRIM(INSERT(str, start, end - start + 1, ""));
           END LOOP;
           END');

标签:sql-function,sql,mysql,php,pdo
来源: https://codeday.me/bug/20191123/2065426.html