Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pdo defining a function an then using it in a select statement

My query is somewhat like this :

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

I'm using php's PDO which doesn't allow more than 1 statements in a $pdo->query() , so instead I decided that I'd split the query into two, so I execute the CREATE FUNCTION query using $pdo->exec() and then use $pdo->query() on the select statement.

However, I get the error on execution of select statement that FUNCTION database.func does not exist. How do I solve this? when I run it in phpmyadmin as a single query it works fine

Edit : PHP code :

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));
like image 731
Peeyush Kushwaha Avatar asked Sep 06 '25 03:09

Peeyush Kushwaha


1 Answers

Create a user defined function using PDO simply works by exec, no delimiter is required. Here $db is PDO instance.

$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');
like image 163
Pankaj Garg Avatar answered Sep 08 '25 00:09

Pankaj Garg