Question

I'm developing a PHP script with MySQL database connection. The problem I'm having is my queries have to be optimized because I handle a lot of information and, in order to do so, I'm making large queries.

To write an example I won't write a large query but one for you to be able to see what I need:

SELECT db1.name, db1.pass, db1.user_id, db2.datetime, db2.user_id 
FROM database1 db1, database2 db2 
WHERE db1.name = 'name' 
AND db1.pass = 'pass' 
AND db1.user_id = db2.user_id

What I need is to know if the query fails because the name and pass are incorrect, or because the user_id is not equal in both tables.

Basically, I need to return an Error Number or something like that in the query to be able to identify the error in the query and to output a custom message: "Your user and password are incorrect." or "You don't have permissions in database2."

Thanks in advance!

Était-ce utile?

La solution

The SQL SELECT statement is not designed to return an "error number" or "error message", when no rows are returned because a particular predicate was not satisfied.

(By "query fails" and "error in the query", I assume you are referring to the query not returning any rows because the predicates were not satisfied (i.e. whether any rows "matched" the WHERE clause), rather than an actual MySQL error.)

Given the example query in the question, that could be rewritten, to do this kind of check.

For example:

SELECT IF(db1.name IS NULL
         ,'Your user and password are incorrect.'
         ,IF(db2.user_id IS NULL
           ,'You don''t have permissions in database2.'
           ,''
       ) AS message
     , db1.name
     , db1.pass
     , db1.user_id
     , db2.datetime
     , db2.user_id 
  FROM (SELECT 1 AS i) i
  LEFT
  JOIN database1 db1
    ON db1.name = 'name' 
   AND db1.pass = 'pass' 
  LEFT
  JOIN database2 db2
    ON db1.user_id = db2.user_id

But the fact you can write such a statement does not mean this is a good approach. (There has to be some name for this anti-pattern.)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top