I have a multiple SQL query that runs fine when executed through PHPMyAdmin (on MariaDB) and returns one result, but when executed as a statement through a PDO object, it returns NULL and no errors.
If I change the $sql so it´s just a single SQL query, it returns a result fine.
I have put an "echo" in the code to print out the $sql that is executed and when I copy past it into PHPMyAdmin I get a result.
SELECT GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(`Translations`.`ColumnName` = "', `Translations`.`ColumnName` , '", `Translations`.`Translation`, "")) AS "', `Translations`.`ColumnName`,'"')) INTO @SQL FROM `Translations`;
SET @sql = CONCAT('SELECT `RowID`, `ImageName`, ', @sql,' FROM `Events` LEFT JOIN `Translations` ON `Events`.`ID` = `Translations`.`RowID` WHERE `Translations`.`Language` = "es" GROUP BY `RowID`');
PREPARE stmt FROM @sql; EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Here's the function where I execute the SQL statement:
<?php
function getData(string $tableName, int $rowID, string $language)
{
global $cc_db_conn;
try{
$sql = "SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(`Translations`.`ColumnName` = \"', `Translations`.`ColumnName` , '\", `Translations`.`Translation`, \"\")) AS \"', `Translations`.`ColumnName`,'\"')) INTO @SQL FROM `Translations`;
SET @sql = CONCAT('SELECT `RowID`, `ImageName`, ', @sql,' FROM `Events` LEFT JOIN `Translations` ON `Events`.`ID` = `Translations`.`RowID` WHERE `Translations`.`Language` = \"es\" GROUP BY `RowID`');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;";
//$sql = "SELECT * FROM `Events` WHERE `FromDate`>=CURRENT_DATE ORDER BY `FromDate` ASC LIMIT 10";
echo "<br><br>".$sql."<br><br>";
$stmt = $cc_db_conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetch();
}
catch(Exception $e)
{
echo $e->getMessage();
}
if ($result==NULL)
{
echo "No results<br>";
}
else
{
echo '<DIV class="event">
<DIV class="title">'. $result->RowID.'</DIV>
<DIV class="summary">'. $result->ImageName.'</DIV>
<DIV class="description">'. $result->Name.'</DIV>
</DIV>';
}
}
?>
Where I open the db connection I have added the following:
$cc_db_conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);