Can someone please tell me what is wrong with the syntax shown below for MySQL 5.5
$sql = "select tm.*, tt.tax_rate as tax from ".TABLE_MEMBER." tm left join ".TABLE_TAX_RATES." tt on tt.tax_rates_id = tm.rent_tax_class_id where plan_id='".$planid."'";
$rs = tep_db_query($sql);
$row_days = tep_db_fetch_array($rs);
if (!$row_days['tax']) $row_days['tax'] = 0;
tt.* AS is invalid syntax because you cannot alias multiple columns. You have to write out each column individually (and alias those as needed), or simply accept using *, which you should avoid using in production. The query in your comment is different from the one in your question which should not cause this error.
You should also be using properly parameterized queries -- your query is vulnerable to injection.
You missed to mention table alias in where clause
The sql should be
$sql = "select tm.*, tt.tax_rate as tax from ".TABLE_MEMBER." tm left join ".TABLE_TAX_RATES." tt on tt.tax_rates_id = tm.rent_tax_class_id where tm.plan_id='".$planid."'";
or
$sql = "select tm.*, tt.tax_rate as tax from ".TABLE_MEMBER." tm left join ".TABLE_TAX_RATES." tt on tt.tax_rates_id = tm.rent_tax_class_id where tt.plan_id='".$planid."'";
Related
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'];
I'm trying to get these three items out of my database however I don't think I'm using the correct JOIN.
The 3 fields I need are:
fldDate - Which is held inside of tblCompetition
fldCatName - Which is held inside of tblCategory
fldName - Which is held inside of tblImage
I have posted my Diagram of my tables with their field names to help explain:
My Query I have at present is:
$query ="SELECT `fldDate`, `fldCatName`, `fldName`
FROM `tblMembEntComp`
JOIN `tblImage` ON `tblMembEntComp`.`fldMemberID` = `tblMembEntComp`.`fldMemberID`
JOIN `tblCompetition` ON `tblMembEntComp`.`fldCompID`= `tblCompetition`.`fldCompID`
WHERE `fldMemberID` = 1;"
The error appearing is: Unknown column 'fldCatName' in 'field list', can someone explain where I'm going wrong.
You are not joining the tblCategory table with the tblImage table. That is why MySQL cannot find the field fldCatName
Your query should be
$query ="SELECT `fldDate`, `fldCatName`, `fldName`
FROM `tblMembEntComp`
JOIN `tblImage` ON `tblMembEntComp`.`fldMemberID` = `tblMembEntComp`.`fldMemberID`
JOIN `tblCompetition` ON `tblMembEntComp`.`fldCompID`= `tblCompetition`.`fldCompID`
JOIN `tblCategory` ON `tblImage`.`fldCatID` = `tblCategory`.`fldCatID`
WHERE `tblMembEntComp`.`fldMemberID` = 1;"
You might want to use different kinds of joins depending on your use case. This will help
I have some trouble when I Joining 3 tables, I use mysqli procedural. here's my query..
$select = $connection->conn->query('SELECT * FROM master_beli, supplier, karyawan WHERE supplier.id_supplier = master_beli.id_supplier AND karyawan.id_karyawan = master_beli.id_karyawan');
After that I viewing with this code
while($fetchData = $select->fetch_array()){
echo $fetchData['id_karyawan'].'<br>';
}
I don't know where the problem is, because I use this query a few months ago and it's worked, but now isn't work..
Could be your issue is related to the ambiguity of the column name id_karyawan present in two tables try use an explicit alias or a explict column naming eg :
$select = $connection->conn->query('SELECT master_beli.id_karyawan
FROM master_beli
INNER JOIN supplier ON supplier.id_supplier = master_beli.id_supplier
INNER JOIN karyawan ON karyawan.id_karyawan = master_beli.id_karyawan');
and as suggested in the code above you should use explicit join sintax ..for better readibilty
(the use of implict join sintax is not more promoted in sql)
SELECT master_beli.id_supplier,master_beli.id_karyawan
FROM master_beli
join supplier on supplier.id_supplier = master_beli.id_supplier
join karyawan on karyawan.id_karyawan = master_beli.id_karyawan;
it work on mysql
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).
hey guys im trying to query something in php but the WHERE is a index from array this is what i did
$data=array();
while ($row = mysql_fetch_array($result))
{
$item = array(
'sec_id'=>$row['section_id'],
'sec_name'=>$row['section_name'],
'sec_dept'=>$row['section_department'],
'sec_lvl'=>$row['section_level'],
'advisory_id'=>$row['advisory_id'],
'first_name'=>$row['f_firstname'],
'last_name'=>$row['f_lastname'],
'middle_name'=>$row['f_middlename'],
'advisor_id'=>$row['faculty_id'],
);
$get_subjects = "SELECT subject_name
FROM subjects
WHERE level = '".$row['section_level']."' ";
$result_get_subjects =mysql_query($get_subjects)or die(mysql_error());
$subjects_count = mysql_num_rows($result_get_subjects);
$check_archive_subjects = " SELECT b.subject_name
FROM registrar_grade_archive a
LEFT JOIN subjects b ON(a.subject_id=b.subject_id)
LEFT JOIN section c ON(a.section_id = c.section_id)
WHERE a.advisor_faculty_id ='".$row['faculty_id']."'
WHERE a.section_id ='".$row['section_id']."'
GROUP BY b.subject_name ASC
" ;
$query_checking =mysql_query($check_archive_subjects)or die(mysql_error());
$subjects_count_sent = mysql_num_rows($query_checking);
but unfortunately i got an error in $check_archive_subjects that says:
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 'WHERE a.section_id ='24'
is there any other way to put an array index in where clause in mysql. I know mysql is deprecated and ill be switching to mysqli after i finished this project so pardon me guys. thanks in advance
Multiple WHERE conditions should be joined using boolean keywords AND or OR. You don't issue multiple WHERE clauses.
Also, please read this regarding the MySQL extension - https://stackoverflow.com/a/12860046/283366
Try the below query
SELECT b.subject_name
FROM registrar_grade_archive a
LEFT JOIN subjects b ON(a.subject_id=b.subject_id)
LEFT JOIN section c ON(a.section_id = c.section_id)
WHERE a.advisor_faculty_id ='".$row['faculty_id']."' AND a.section_id ='".$row['section_id']."'
GROUP BY b.subject_name ASC
Explanation
Using multiple WHERE clause like above is not accepted in MySQL. Try replacing the 2nd WHERE using an AND or using an OR depending on your requirement. I have used AND