Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute mysql script with variables using PHP::PDO?

Tags:

sql

php

mysql

pdo

I am unable to execut long script the pdo throws an exception:

SQLSTATE[HY000]: General error

If I submit script which does not contain variables it runs w/o problem. The same script runs on phpmyadmin interface.

Here is my code snippet:

 try {
 $dsn = "mysql:host=" . DB_SERVER . ";dbname=" . DB_DEFAULT;
 $db = new PDO($dsn, DB_USER, DB_PASS);
 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 $q = $db->query($query);
 if (!$q) {
 echo $db->errorInfo();
  } else {
        $rows = $q->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (PDOException $e) {
    var_dump($e);
 }

Here is some test which does not execute by PDO:

SET @ra_LMC:=80.9;
SELECT @ra_LMC;

How I should execut with pdo the multi line scripts?

Thanks
Arman.

like image 296
Arman Avatar asked Jan 13 '11 17:01

Arman


People also ask

What is PDO :: Param_str in PHP?

PDO::PARAM_STR. Represents SQL character data types. For an INOUT parameter, use the bitwise OR operator to append PDO::PARAM_INPUT_OUTPUT to the type of data being bound. Set the fourth parameter, length , to the maximum expected length of the output value.

What is PDO in php MySQL?

Introduction ¶ PDO_MYSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to MySQL databases. PDO_MYSQL uses emulated prepares by default. MySQL 8. When running a PHP version before 7.1. 16, or PHP 7.2 before 7.2.

What does PDO -> query return?

Return Value If the call succeeds, PDO::query returns a PDOStatement object. If the call fails, PDO::query throws a PDOException object or returns false, depending on the setting of PDO::ATTR_ERRMODE.


2 Answers

PDO does not allow the execution of multiple statements in one query() request. But your @ra_LMC variable should be visible in the current connection, so you can put your second line (SELECT) into a new query() call.

To read a whole script, you have to parse the file and run each statement with a call to query().

like image 106
cytrinox Avatar answered Oct 05 '22 09:10

cytrinox


PDO can only execute one statement at a time. You can ether run the SET and SELECT as 2 separate statements. Or you can set the variable using FROM.

SELECT @ra_LMC FROM (SELECT @ra_LMC:=80.9) q
like image 21
Rocket Hazmat Avatar answered Oct 05 '22 10:10

Rocket Hazmat