Execute multiple queries in PHP - 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.

Related

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 JOIN pass PHP variable to two tables

I have the following MySQL query in PHP that passes a variable to complete the query:
SELECT * from mobile_tech WHERE uid=$uid order by timestamp DESC limit 0,1
I have the following MySQL JOIN that provides data from two tables:
SELECT mobile_tech.latitude, mobile_tech.longitude, mobile_tech.timestamp, mobile_tech.uid, gbl_qemplisting.EmpNo, gbl_qemplisting.FirstName, gbl_qemplisting.LastName
FROM mobile_tech, gbl_qemplisting
WHERE mobile_tech.uid=gbl_qemplisting.EmpNo AND date(timestamp)='$currentday'
group by uid
I need to combine these two queries into one with a JOIN and still passing the $uid variable to complete the query.
I've tried the following and it did not work:
SELECT mobile_tech.latitude, mobile_tech.longitude, mobile_tech.timestamp, mobile_tech.uid, gbl_qemplisting.EmpNo, gbl_qemplisting.FirstName, gbl_qemplisting.LastName
FROM mobile_tech, gbl_qemplisting
WHERE mobile_tech.uid=$uid AND gbl_qemplisting.EmpNo=$uid AND date(timestamp)='$currentday'
Your query will return a cross product between the mobile_tech and gbl_emplisting rows for $uid. If you just want one row, as in the first query, use ORDER BY and LIMIT similarly.
SELECT mobile_tech.latitude, mobile_tech.longitude, mobile_tech.timestamp, mobile_tech.uid, gbl_qemplisting.EmpNo, gbl_qemplisting.FirstName, gbl_qemplisting.LastName
FROM mobile_tech, gbl_qemplisting
WHERE mobile_tech.uid=$uid AND gbl_qemplisting.EmpNo=$uid AND date(timestamp)='$currentday'
ORDER BY mobile_tech.timestamp
LIMIT 1
Please try with this and say the result
SELECT mobile_tech.latitude,
mobile_tech.longitude,
mobile_tech.timestamp,
mobile_tech.uid,
gbl_qemplisting.EmpNo,
gbl_qemplisting.FirstName,
gbl_qemplisting.LastName
FROM mobile_tech inner join gbl_qemplisting
on mobile_tech.uid=gbl_qemplisting.EmpNo
where mobile_tech.uid=$uid AND date(timestamp)='$currentday'

Combine two different select and update statements

I have one select query and one update query and I want to combine both of them.
The select query is like:
select questionDesc from myTable
where
questionId >= (
select currentQuestionid from userTable
where userId='1'
)
and questionId <= (
select currentQuestionid+4 from userTable
where userId='1'
)
For user=1, this query tries to fetch all the question Descriptions from myTable whose questionId lies between currentQuestionid and currentQuestionid+4 (currentQuestionid is a column specific to a user in the userTable). I will later use this result in my front-end.
Now, I want to update the currentQuesionid to currentQuestionid+5. This could be achieved using:
UPDATE userTable SET currentQuesionid = currentQuestionid+5 WHERE userId ='1'
I want to achieve both these queries in one database hit so as to improve the performance.
Is there any way to combine the two. I am using WAMP and the code is written in php scripts.
Any help is appreciated.
I think I have found the answer.
For combining multiple queries together we can use mysqli_multi_query() function. It is available for MySQL server versions 4.1.3 and newer. It takes multiple queries as input parameter and performs them in one db hit.
for example:
//sql queries should be separated by semi-colons
$sql = "SELECT Lastname FROM Persons ORDER BY LastName;";
$sql .= "SELECT Country FROM Customers";
// Execute multi query
if (mysqli_multi_query($con,$sql))
{
do
{
// Store first result set
if ($result=mysqli_store_result($con)) {
// Fetch row one and one
while ($row=mysqli_fetch_row($result))
{
printf("%s\n",$row[0]);
}
// Free result set
mysqli_free_result($result);
}
}
while (mysqli_next_result($con));
}
Source: http://www.w3schools.com/php/func_mysqli_multi_query.asp

PHP Prepared Statement variable binding error with subquery

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).

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