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'");
Related
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.
I need to get specific columns from three tables through joins.every time it goes wrong.my code is
$saf=mysqli_query($db , "select pod.mobile, tpaidamount.Aptdate, follow.cent, pdate, time from pod,tpaidamount, follow where tpaidamount.pid = follow.pid and pod.Customer Id = tpaidamount.pid and pod.Customer Id =follow.pid ");
$i=1;
while($sfg=mysqli_fetch_assoc($saf) or die(mysqli_error($db)))
;
?>
pod,tpaidamount,follow are tables and other coloumns
Getting 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 'Id = tpaidamount.pid and pod.Customer Id =follow.pid' at line 1
is it a typo? Is setfollowup.pid or follow.pid?
select pod.mobile, tpaidamount.Aptdate, follow.cent, <table>.pdate, <table>.time
from pod, tpaidamount, follow
where tpaidamount.pid = follow.pid
and pod.`Customer Id` = tpaidamount.pid
and pod.`Customer Id` = follow.pid
You shouldn't Ever create columns names with spaces. The name: "pod.Customer Id" is a Bad attribute name, and you need to avoid use names like datatypes (or any SGBD reserved word) like: 'date', 'time', 'char', 'table', 'column'....
However, if you need to do it, try this SQL:
SELECT p.mobile
, t.Aptdate
, f.cent
, ???.pdate
, ???.`time`
FROM pod AS p
JOIN tpaidamount AS t ON o.`Customer Id` = t.pid
JOIN follow AS f ON t.pid = f.pid ON p.`Customer Id` = f.pid
Use alias for easy coding SQL queryes. Ex: table_name AS tn, table_a_name AS tan.
!!! I sugest you to watch some basic SQL Lessons.
Good Luck.
There is a minor problem in my query and I can't seem to figure it out. I am using select into statement to copy one table's column to another. The browser is showing error the following error:
undeclared variable:new_tbl
When I open phpmyadmin, there is no new_tbl added to the particular database. Please tell me what's wrong with it. And the new-tbl does not already exists.
$sqli = "SELECT * INTO `new_tbl` FROM `order`";
$query = mysqli_query($con,$sqli);
if($query) {
echo "SELECT INTO query worked...";
} else {
echo "ERROR:".mysqli_error($con);
}
MySQL does not support select into. Use create table as:
create table new_tbl as
SELECT * FROM `order`;
By the way order is a really bad name for a table because it is a SQL keyword.
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).
This may be simple to solve but I'm having trouble with this piece of code - I'm a self taught newbie with PHP, and the code I've come up with doesn't seem to want to work.
The pages are for an online entry system for a sports competition. Judges' details are stored in table "club_judges", and users can enter them into a competition by copying them into "competition_judges". This is done via a checkbox form in a table.
I want to add functionality whereby judges who are already added to the competition do not appear in the import form, however my code does not seem to work. I am using a unique field of "bg_number" (the sport's identification number) to search for an existing entry.
Current code:
$existing_judges = mysql_query("SELECT bg_number FROM competition_judges WHERE competition='Test Competition'");
$existing_judges_fetch = mysql_fetch_array($existing_judges);
$existing_judges_array = "('" . implode( "', '", $existing_judges_fetch ) . "');" ;
$query = "SELECT * FROM club_judges WHERE (`club`='Test Club') AND (`bg_number` NOT IN '$existing_judges_array') ORDER BY name ";
$result = mysql_query($query) or die(mysql_error());
Error displayed:
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 ''('1234567', '1234567');') ORDER BY name' at line 1
For reference 1234567 is the bg_number for my test judge.
Any help would be greatly appreciated!
why dont u use just one query
SELECT *
FROM club_judges
WHERE `club`='Test Club'
AND `bg_number`
NOT IN (SELECT bg_number FROM competition_judges WHERE competition='Test Competition')
ORDER BY name
Use can use a single query instead like this:
$query = "SELECT * FROM `club_judges` WHERE `club`='Test Club'
AND
`bg_number` NOT IN
(SELECT `bg_number` FROM `competition_judges` WHERE `competition`='Test Competition')
ORDER BY `name` ";
$existing_judges_fetch = mysql_fetch_array($existing_judges);
$result = mysql_query($query) or die(mysql_error());
here's a JOIN version
SELECT a.*
FROM club_judges a
LEFT JOIN competition_judges b
ON a.bg_number = b.bg_number AND
b.competition='Test Competition'
WHERE b.bg_number IS NULL AND
a.club = 'Test Club'
ORDER BY a.name
To fully gain knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins