what is wrong with this line of SQL? - mysql

SELECT Batch.NumStud
FROM Batch
WHERE CourseID='$courseid'
INNER JOIN Course
ON Batch.CourseID=Course.CourseID"
an error that says mysql_fetch_array(): supplied argument is not a valid MySQL result resource in <b>F:\AppServ\www\anNoECourse.php
is shown.This code was written to feed in data to a google chart.

You put SQL in wrong order (JOIN and WHERE are switched):
SELECT Batch.NumStud
FROM Batch INNER JOIN Course
ON Batch.CourseID = Course.CourseID
WHERE Course.CourseID = '$courseid'
It seems, that your query can be simplified (check your data):
select Batch.NumStud
from Batch
where Batch.CourseID = '$courseid'

I think the error is a bit more complex. Due to the fact that your SQL is invalid, you're not getting a result set. This case is not handled correctly by your PHP code!
So in addition to correcting your SQL as the others have suggested, please make sure to handle the case where you get no results or your query results in an error correctly in your PHP code!
The second part to your solution is as follows:
$result = mysql_query(...);
if ($result)
{
while (...)
...
}
This makes sure that mysql_query actually returned a result set and not false, which it does in case of errors (due to your invalid SQL code, but also in other cases). So just fixing your SQL is not enough to make your script error proof.
But again, do no longer use the mysql_.... functions! They are deprecated.

Related

MySQLWorkbench returns 'OK' instead of returning rows

ok so, im trying to generate "TOP 5 name of childcare centres that is popular among the SC and SPR" and i got an "OK" instead of "xxx rows returned" in mySQLWorkbench output. Issit possible for anyone of you to check if my query is correct??
mySQLWorkbench version is 8.0.18
SELECT centre_service.centre_name
FROM centre_service
WHERE centre_service.centre_code = centre.centre_code AND (type_of_citizenship = "SC" OR type_of_citizenship = "SPR") AND centre_name = (
SELECT centre.centre_name
FROM centre
GROUP BY centre_name LIMIT 5
);
This answer does not tackle the errors in the query, but helps to answer the question about why neither an error is seen nor data rows, and what can be done about it.
MySQL Workbench does not handle all types of query errors nicely. Sometimes it just returns "OK" with no rows. I have seen this with, for example, illegal mixed collation errors.
When this happens, just issue this in the query tab:
show errors;
This will return one or more errors, each with a level, a code and a message. For example, my query (details not important) returned "OK" and nothing else. Then show errors gave me this:
Level
Code
Message
Error
1267
Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT) for operation '='
I cannot say for certain, but it seems like [some?] run-time errors are prone to this problem, rather than syntax errors that are caught immediately.
Try this query. You had 2 mistakes: using reference of a table from subquery in an outer scope (replaced to the inner scope) and using comparison operator to the multiple values (changed to IN).
SELECT centre_service.centre_name
FROM centre_service
LEFT JOIN (
SELECT centre_name
FROM centre
GROUP BY centre_name LIMIT 5
) centre ON centre.centre_name = centre_service.centre_name
WHERE
(type_of_citizenship = "SC" OR type_of_citizenship = "SPR") AND
centre_service.centre_code = centre.centre_code;

MySQL Query Error Validation

I running a Mysql Query to select some data, Sometimes i get a error called
mysql_fetch_assoc() expects parameter 1 to be resource, boolean given
when i executed this following code,
$result = $this->db->execute($sql);
for ($i = 0; $data[$i + 1] = mysql_fetch_assoc($result); $i++);
array_pop($data);
how do i optimize this coding to prevent any errors ?
is there anything wrong with it ? should i ignore this error ?
That means that the query is buggy, whyever, most likely because you construct it using components from sources which you do not really check enough. A buggy statement throws an error (since no result can be computed). That error is returned as false instead of a mysql result ressource. Since you do not check if the query succeeded but blindly try to retrieve details from the result, you get this second error.
So there are four things you have to invest into:
you should always check if a query succeeded at all:
enclose your query into a conditional: if (FALSE!==($result=$this->db->execute($sql))) and only retrieve from the result ressource if that condition resolves to true.
make sure you really (really!) check all input data you use to construct your query. Checking here also means to encode and escape it correctly, also see point 4. for this.
in cases like this it is important to analyze what exactly it is that is going wrong. There is little sense in guessing what might be going wrong. So in addition to checking if the query succeeded at all (1.) you should also take a look at the error message mysql throws if this is not the case. Use the method mysql_error() for this. It is well documented just as every other function too.
you should rework your code and migrate from phps old, long deprecated mysql extension to either mysqli or PDO. Both are php extensions that offer more security against constructing buggy statements. Read about "prepared statements" and "parameter binding" for this.

Codeigniter Active records complex query

> *1. I need to write this in Active records *
i need to join these 3 tables , but the condition for join is very very selective
$this->db->select(name);
$this->db->from('table0');
$this->db->join('table1','(table1.id=0 AND table0.feild1 = table1.feild1) OR (table1.id=1 AND table0.feild2 = table1.feild2)') // <--- how to write this is my question
i could do a simple join but the main problem is achieving the condition in the join that i have mentioned above.Also this is a small part of a very , very ! big query so i really cant change it back to the native sql query like :
$this->db->query('//entire sql query'); //cant do this, need to write ACTIVE RECORDS
when i write the active records , firebug throws me an error saying :
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 ') OR
any suggestions ?
To be honest, I don't know that it is possible. CI doesn't use true Active Records, so each method has very rigid parameters, and I don't see any that can be tricked into performing the task you need.
What I would try is re-writing your query a bit:
$this->db->select(name);
$this->db->from('table0');
$this->db->join('table1','(table1.id=0 AND table0.feild1 = table1.feild1)', LEFT);
$this->db->join('table1','(table1.id=1 AND table0.feild2 = table1.feild2)', LEFT);
$this->db->where('(table1.id=0 AND table0.feild1 = table1.feild1)');
$this->db->or_where('(table1.id=1 AND table0.feild2 = table1.feild2)');
I believe this query would return the correct values, but you'll certainly want to thoroughly test it. Hope this at least points you in the right direction.

MySQL Error 1172 - Result consisted of more than one row

I'm getting this error from MySQL when running a query inside a stored procedure:
Error Code: 1172
Result consisted of more than one row
I understand the error: I'm doing a SELECT (...) INTO (var list), and thus the query is required to return a single row. When I use LIMIT 1 or SELECT DISTINCT, the error goes away.
However: when I run the original query manually (without LIMIT or DISTINCT), it does return a single row. So I'm suspecting I may have bumped into a MySQL bug. Does anyone know what could be happening?
EDIT
I'm posting the SQL as requested. Everything that starts with an underscore is a variable declared earlier inside the procedure. When I test it, I'm replacing _cd_pai_vc with the ID for the record that is causing the problem.
SELECT a.valor, IFNULL(p.valor, 0), fn_cd2alias(ra.cd_registro), fn_cd2alias(IFNULL(p.valor,0))
INTO _valor, _cd_pai_vc, _alias_verbete, _alias_pai
FROM dados_registros ra
INNER JOIN dados_varchar255 a
ON a.cd_registro = ra.cd_registro
AND a.fl_excluido = 0
AND a.alias = 'vc-verbetes-termo'
LEFT OUTER JOIN dados_registros rp
INNER JOIN dados_int p
ON p.cd_registro = rp.cd_registro
AND p.fl_excluido = 0
AND p.alias = 'vc-remissoes-termo referenciado'
INNER JOIN dados_int pt
ON pt.cd_registro = rp.cd_registro
AND pt.fl_excluido = 0
AND pt.alias = 'vc-remissoes-tipo remissao'
AND fn_cd2alias(pt.valor) = 'hierarquica'
ON ra.cd_registro = rp.cd_entidade
AND rp.fl_excluido = 0
AND fn_cd2alias(rp.cd_modulo) = 'vc-remissoes'
WHERE ra.cd_registro = _cd_pai_vc
AND ra.fl_excluido = 0;
I had the similiar issue and when I put table alias it worked like a charm.
SELECT t.tax_amount,t.tax_percentage FROM nepse_tax t
I had this problem and found it went away when I used both table name and column name in select statements, even simple ones.
The issue i had was IN parameter and the column name both were same so altered IN parameter name and it worked
I have experienced the same error in mysql.
MySQL Error 1172 - Result consisted of more than one row
Then I saw the question:
mysql stored procedure error (1172, 'Result consisted of more than one row')
But it was not I meant to ask. LIMIT 1;-wasn't up to my expectation. It will just return the first row for all the case.
Then I started looking at this one deeply and now I got the solution.
This case happend because the code for stored procedure returns multiple rows and that was because I had many extra spaces and tab characters in my code[the code I wrote for stored procedure] and when I removed them with just one/two appropriate tab chars- it was just like a flying machine.
I don't know if it is the same case that you are experienced with. Anyway give a try.
Thank you.
I had the same problem, the solution by Nava Bogatee worked like a charm,
below is a part of the procedure
select attendance
into brb
from Stud
where Rno like rno;
This didn't work I have no idea why.
Then I changed this to
select t.attendance
into brb
from Stud t
where t.Rno like rno;
and it worked.
I guess due to some reason the Rno column is returning all the values in the table, that is why the multiple row error.

Hibernate Exception on MySQL Cross Join Query

I'm trying to perform a bulk delete of an object, Feature, which has a birdirectional ManyToOne relationship with another class, FeaturesMetadata. I'm having a SQLGrammerException thrown.
The hql I'm using:
String hql = "delete from Feature F where F.featuresMetadata.stateGeoId = :stateGeoId";
Turning on show SQL, the following is generated:
delete from FEATURE cross join FEATURESMETADATA featuresme1_ where STATEGEOID=?
Running the SQL directly in the db client gives this exception:
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 'cross join FEATURESMETADATA featuresme1_ where stategeoid='01'' at line 1
Since the generated SQL is throwing the Exception, I tried changing dialects from MySQL5InnoDBDialect to MySQLInnoDBDialect, but no change.
Can anyone assist?
You may not have joins in such a HQL query. Quote from the reference documentation:
No joins, either implicit or explicit, can be specified in a bulk HQL
query. Sub-queries can be used in the where-clause, where the
subqueries themselves may contain joins.
So I guess something like this should work:
delete from Feature F where F.id in
(select f2.id from Feature f2 where f2.featuresMetadata.stateGeoId = :stateGeoId)
I had the same issue and struggled to find a sensible answer. It seems that, even if you get this approach to work, the SQL generated is highly inefficient (according to what I have read).
So I took a step back and did the following:
List<Properties> props = propDao.findPropertiesByHotelCode(hotel.getCode());
propDao.deleteInBatch(props);
propDao.flush();
Basically rather tan trying to 'delete where', I'm doing a select where and then deleting in batch the set that I retrieved.
Hope this helps.
This is indeed rather poor from Hibernate. But you can solve it like this in a repo: (at least in PostgreSQL, not sure if this syntax should be modified for MySql)
#Modifying
#Query(nativeQuery = true, value = """
DELETE FROM feature f
USING features_metadata fd
WHERE f.features_metadata_id = fd.id AND fd.state_geo_id = :stateGeoId
""")
void deleteByStateGeoIdId(#Param("stateGeoId") UUID stateGeoId);