PHP Prepared Statement variable binding error with subquery - php

I have a query with a few subqueries like so
SELECT ...
FROM (SELECT ...
FROM ...
GROUP BY ...) as speedLimitCalc INNER JOIN
(SELECT ...
FROM date a INNER JOIN HOURLY_TEST b ON a.[FULL_DAY_DT] = b.DATE
WHERE (b.DATE BETWEEN '".$date_s."' AND '".$date_e."')
AND HOUR BETWEEN ".$time_s." AND ".$time_e."
AND(LKNO BETWEEN '".$lkno_s."' and '".$lkno_e."')
AND RDNO= '".$rdno."'
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (".$dayquery.")
GROUP BY RDNO, LKNO, PRESCRIBED_DIRECTION, CWAY_CODE) as origtable ON ...
,(SELECT ...
FROM [Dim_date]
WHERE (FULL_DAY_DT BETWEEN '".$date_s."' AND '".$date_e."')
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (".$dayquery.") ) as c
ORDER BY ...
where I am inserting variables in the inner query where clause.
I am trying to parametrize this query using odbc_prepare and odbc_execute, however I am running into issues of binding the variables. At present, when I use the following
$result = odbc_prepare($connection, $query);
odbc_execute($result)or die(odbc_error($connection));
to run this query, everything works fine. However, when I try to bind a variable, such as
AND RDNO= ?
...
odbc_execute($result, array($rdno))or die(odbc_error($connection));
I get the following error message.
PHP Warning: odbc_execute() [/phpmanual/function.odbc-execute.html]: SQL error: [Microsoft][ODBC SQL Server Driver]Invalid parameter number, SQL state S1093 in SQLDescribeParameter
My guess is that it's because I'm binding a variable in a subquery, since this procedure works when the Where clause is in the top Select query.
I was wondering whether anyone else has encountered this issue before, and how they solved it? Thanks

Fixed the issue by removing the need for parameters in the subquery by separating the query into multiple queries using temporary tables.
$query = "SELECT ...
INTO ##avgspeedperlink
FROM Date a INNER JOIN HOURLY_TEST ON a.[FULL_DAY_DT] = b.DATE
WHERE (b.DATE BETWEEN ? AND ?)
AND HOUR BETWEEN ? AND ?
AND(LKNO BETWEEN ? and ?)
AND RDNO= ?
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (?,?,?,?,?,?,?)
GROUP BY RDNO, LKNO, PRESCRIBED_DIRECTION, CWAY_CODE";
$result = odbc_prepare($connection, $query);
odbc_execute($result, array($date_s,$date_e,$time_s,$time_e,$lkno_s,$lkno_e,$rdno,$daysanitised[0],$daysanitised[1],$daysanitised[2],$daysanitised[3],$daysanitised[4],$daysanitised[5],$daysanitised[6]))or die(odbc_error($connection));
$query = "SELECT ...
INTO ##daysinperiod
FROM [RISSxplr].[dbo].[Dim_date]
WHERE (FULL_DAY_DT BETWEEN ? AND ?)
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (?,?,?,?,?,?,?)";
$result = odbc_prepare($connection, $query);
odbc_execute($result, array($date_s,$date_e,$daysanitised[0],$daysanitised[1],$daysanitised[2],$daysanitised[3],$daysanitised[4],$daysanitised[5],$daysanitised[6]))or die(odbc_error($connection));
$query = "SELECT ...
FROM ##avgspeedperlink, ##daysinperiod
ORDER BY LKNO, OUTBOUND
drop table ##avgspeedperlink
drop table ##daysinperiod";
Note that I had to use double ## for making the temporary tables (single # means that table is local to the query, ## means that the temporary table becomes global for multiple queries).

Related

Query works in phpmyadmin but same query won't return in PHP script

This is NOT a duplicate. None of the already existing threads have the same problem as me.
I have a database that stores athlete performances. It contains sessions, each session has sets, each set has "tables" (such as 4x100m, 12x50m and so on), and each table has times. I also have a table for athletes. Each athlete has an ID, each time links with the athlete through the AthleteID. Every session, set, timetable and time also have each unique IDs, used to link them with each other.
I want to make it so that when passing a session ID, it will return all the athletes that have at least 1 time in that session. I made a page that gets requests and the session ID is passed as GET search data (will make it POST later on). The request system works fine, but the problem is in the query. To do it I used inner joins to connect each table. This is my query (it is not the fastest method, but that's for another thread):
$q = "SET #evID = " . $method['sessID'] . ";";
$q .= "SELECT `athletes`.* FROM `events`
INNER JOIN `sets` ON `sets`.`EventID` = `events`.`EventID`
INNER JOIN `timetables` ON `timetables`.`SetID` = `sets`.`SetID`
INNER JOIN `times` ON `times`.`TableID` = `timetables`.`TableID`
INNER JOIN `athletes` ON `athletes`.`ID` = `times`.`AthleteID`
WHERE `events`.`EventID` = #evID
AND `times`.`TimeID` IN(
SELECT MIN(`TimeID`)
FROM `times`
WHERE `TableID` IN(
SELECT `TableID`
FROM `timetables`
WHERE `SetID` IN(
SELECT `SetID`
FROM `sets`
WHERE `EventID` = #evID
)
)
GROUP BY `AthleteID`
)";
Every single time I ran that in phpmyadmin it returned all the athletes, and the data was correct. However, when I run it in my script, the query value is false (such as if there is an error). I tried debugging like this:
$r = $db -> query($q);
var_dump($q);
var_dump($r);
var_dump($db->error);
The query is returned just fine (only difference is lack of newline characters), and when I copy what's returned in phpmyadmin the data is just the same. The rest however:
bool(false)
string(228) "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT `athletes`.* FROM `events` INNER JOIN `sets` ON `sets`.`EventID` = `...' at line 1"
Other users with the same problem have not really gone that far to find out if they're wrong, but I have. This post is not a duplicate, and I didn't find any solutions online. Could this be a problem with the amount of queries in a single string? (There is one for setting #evID and one for the actual selection). Please explain the solution and methods kindly as I'm only 13 and still learning...
As #NigelRen has suggested, please use parameterized prepared statement.
Assuming that
$sessionid is storing the value for EventID, and assuming that this variable is of integer type; and
$conn is the connection
Then for Mysqli, you can use:
//$q = "SET #evID = " . $method['sessID'] . ";";
$sql = "SELECT `athletes`.* FROM `events`
INNER JOIN `sets` ON `sets`.`EventID` = `events`.`EventID`
INNER JOIN `timetables` ON `timetables`.`SetID` = `sets`.`SetID`
INNER JOIN `times` ON `times`.`TableID` = `timetables`.`TableID`
INNER JOIN `athletes` ON `athletes`.`ID` = `times`.`AthleteID`
WHERE `events`.`EventID` = ?
AND `times`.`TimeID` IN(
SELECT MIN(`TimeID`)
FROM `times`
WHERE `TableID` IN(
SELECT `TableID`
FROM `timetables`
WHERE `SetID` IN(
SELECT `SetID`
FROM `sets`
WHERE `EventID` = ?
)
)
GROUP BY `AthleteID`
)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $sessionid, $sessionid);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$row = $result->fetch_assoc(); // fetch data
// do other things you want , such as echo $row['fieldname1'];

Execute multiple queries in PHP

I'm trying to join two views which I create in a query.
The query works fine in MySQL but when I execute it with PHP it looks like it's not actually executing because I can't visualize the two views in the db.
The query I'm executing is the following:
$query1 = "CREATE OR REPLACE VIEW new_tbl AS SELECT
AnagTav.Id,
AnagTav.Riga,
AnagTav.Colonna,
AnagTav.Costo,
AnagTav.Nome,
AnagTav.NumeroPersone,
PrenPic.Data AS Occupato,
PrenPic.IdUtente
FROM `AnagraficaTavoli` AS AnagTav
LEFT JOIN PrenotazioniPicNic AS PrenPic ON PrenPic.IdTavolo = AnagTav.Id
WHERE (PrenPic.Data >= '".$dateFrom."' AND PrenPic.Data <= '".$dateTo."')
OR PrenPic.Data IS NULL
GROUP BY CASE
WHEN AnagTav.Nome != '' THEN AnagTav.Nome
ELSE AnagTav.Id
END
ORDER BY AnagTav.Riga ASC, AnagTav.Colonna;
CREATE OR REPLACE VIEW new_tbl2 AS SELECT
AnagraficaTavoli.*,
Occupato,
IdUtente
FROM AnagraficaTavoli
LEFT JOIN new_tbl ON (AnagraficaTavoli.Id = new_tbl.Id)
WHERE new_tbl.Id IS NULL;";
$result=$conn->query($query1);
After creating the 2 views I execute a second query:
if($result){
$query2 = "SELECT * FROM new_tbl
UNION
SELECT * FROM new_tbl2
ORDER BY Riga ASC, Colonna;";
$resultList=$conn->query($query2);
while($rowList=$resultList->fetch_assoc())
{
//I do stuff here
}
}
$conn is my connection to the db
I tried printing the query and executing it on MySQL, but it works fine.
I don't know why I'm getting this error and I don't know how to solve it.
This might be non obvious, but if you keep your script connected, you can access you temporary tables in separate queries. What you should do is to slice your query into three different operations, especially the "select" being a separate one. Only having single select statement in a query, php will be able to properly fetch resultset.

Running two SQL queries in PHP where the first statement creates a temporary table to be used by the second one

I want to run this long SQL query in PHP.
CREATE TEMPORARY TABLE IF NOT EXISTS info AS (
SELECT warehouse.merchandise_id, SUM(warehouse.prod_quantity) AS qty
FROM warehouse
WHERE warehouse.merchandise_id IN (SELECT merchandise.id FROM merchandise)
GROUP BY warehouse.merchandise_id
);
SELECT LPAD(`id`,8,'0'), prod_title, prod_lcode, prod_price, qty
FROM `merchandise` INNER JOIN info
ON merchandise.id = merchandise_count.merchandise_id;
Here's a quick explanation of what it does: First it creates a temporary table to store some selected data, then it uses the temporary table to INNER JOIN it with data in a permanent table.
I have already tried '$statement1;$statement2;' in PHP, but it gives syntax and access violation error but the given query works flawlessly in phpmyadmin.
I checked other similar posts like this and they suggest to use '$statement1;$statement2;' but it doesn't work for me. My server is running PHP 7. I'm using PHP PDO to connect to my database. Any help is appreciated.
I ran the following and it did work.
$stmt = $pdo->query("
CREATE TEMPORARY TABLE IF NOT EXISTS info AS (
SELECT warehouse.merchandise_id, SUM(warehouse.prod_quantity) AS qty
FROM warehouse
WHERE warehouse.merchandise_id IN (SELECT merchandise.id FROM merchandise)
GROUP BY warehouse.merchandise_id
);
SELECT LPAD(`id`,8,'0'), prod_title, prod_lcode, prod_price, qty
FROM `merchandise` INNER JOIN info
ON merchandise.id = info.merchandise_id;
");
// skip to next rowset, because it's a fatal error to fetch from a statement that has no result
$stmt->nextRowset();
do {
$rowset = $stmt->fetchAll(PDO::FETCH_NUM);
if ($rowset) {
print_r($rowset);
}
} while ($stmt->nextRowset());
Notice I had to fix merchandise_count.merchandise_id to info.merchandise_id in your query, because you have no table reference to merchandise_count.
However, I would recommend you do not bother with multi-query. There's no benefit from concatenating multiple SQL statements in a single call. It's also not supported to use prepared statements when using multi-query, or to define stored routines like procedures, functions, or triggers.
Instead, execute the statements one at a time. Use exec() if the statement has no result set and doesn't need to be prepared statements.
$pdo->exec("
CREATE TEMPORARY TABLE IF NOT EXISTS info AS (
SELECT warehouse.merchandise_id, SUM(warehouse.prod_quantity) AS qty
FROM warehouse
WHERE warehouse.merchandise_id IN (SELECT merchandise.id FROM merchandise)
GROUP BY warehouse.merchandise_id
)");
$stmt = $pdo->query("
SELECT LPAD(`id`,8,'0'), prod_title, prod_lcode, prod_price, qty
FROM `merchandise` INNER JOIN info
ON merchandise.id = info.merchandise_id
");
$rowset = $stmt->fetchAll(PDO::FETCH_NUM);
if ($rowset) {
print_r($rowset);
}
As long as you use the same $pdo connection, you can reference temporary tables in subsequent queries.

Mysql query returns error #1093 - You can't specify target table

I need to check and update with same query my database.
The error says it is not possble to update same table which is included in the select statement. Is there any workaround of this to happen in 1 mysql query? Here is the query:
$query='update option_values_to_products set available="0" where id in (
select ovtp.id from option_values ov,option_values_to_products ovtp,options o where
ovtp.product_id="1657" and ovtp.option_values_id=ov.id and ov.options_id=o.id and
o.name="Size" group by ovtp.id )';
Yes, this is a nagging feature of mysql and there is a workaround to it: wrap the subquery within the IN() clause into another subquery.
update option_values_to_products set available="0" where id in (select id from (
select ovtp.id from option_values ov,option_values_to_products ovtp,options o where
ovtp.product_id="1657" and ovtp.option_values_id=ov.id and ov.options_id=o.id and
o.name="Size" group by ovtp.id ) as t)
Avoid using nested queries for many reasons like performance and memory issue, also it can be very hard to be understood for the next developers
Good practice Split your query into 2 parts :
<?php
$qSelect = 'select ovtp.id from option_values ov,option_values_to_products ovtp,options o where
ovtp.product_id="1657" and ovtp.option_values_id=ov.id and ov.options_id=o.id and
o.name="Size" group by ovtp.id';
$res = DATABASE_MANAGER::exec($qSelect);
$qUpdate = 'update option_values_to_products set available="0" where id in (' . implode(",", $res) .')';
$res2 = DATABASE_MANAGER::exec($qUpdate);

Mysql query for using count on a view in php

I have a query:
$result = mysql_query("CREATE VIEW temporary(IngList) AS (
SELECT DISTINCT (r1.Ingredient)
FROM recipes r1,
recipes r2
WHERE r1.Country = '$temp'
AND r2.Country = '$temp2'
AND r1.Ingredient = r2.Ingredient)
SELECT COUNT(*) FROM temporary");
I want the query to make a view called temporary and have it return a count of the number of rows in the view temporary. I know this code works without the SELECT COUNT(*) because I checked my database and the view is created.
Yet this code throws the error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT COUNT(*) FROM temporary' at line 1
I checked the syntax and it seems to be correct. What seems to be the problem because its quite frustrating.
From the mysql_query documentation:
mysql_query() sends a unique query (multiple queries are not supported)...
You can't create the view, and select from it in a single mysql_query. The view is unnecessary:
$sql = sprintf("SELECT COUNT(DISTINCT r1.Ingredient)
FROM recipes r1
WHERE r.country = '%s'
AND EXISTS(SELECT NULL
FROM recipes r2
WHERE r2.Country = '%s'
AND r1.Ingredient = r2.Ingredient)",
$temp, $temp2);
$result = mysql_query($sql);
For starters you have two statements. What you're writing looks more like a stored procedure. Even if it worked, you would need a semicolon at the end of the first statement. And another statement somewhere saying "DROP VIEW ...." when you are done.
And a temp view is a bit of a non sequitur. I can't find any reference to "CREATE VIEW temporary". Or maybe it's to create a view named temporary with an argument? Views don't take arguments.
I think you might get what you want with a semi-simple SQL statement something like:
$result = mysql_query(
"SELECT COUNT(DISTINCT r1.Ingredient)
FROM recipes r1
JOIN recipes r2 ON r1.Ingredient = r2.Ingredient
WHERE r1.Country = '$temp'
AND r2.Country = '$temp2'");

Categories