Bharanikumar
Bharanikumar

Reputation: 25733

MySQL select query Error

My query is throwing an error like

select id,cHospital from med_patient where cHospital is not null  union
select id,cHospital1 from med_patient where cHospital1 is not null  union
select id,cHospital2 from med_patient where cHospital2 is not null  order by 1

The error is

Notice: Undefined index: cHospital1 in F:\wamp\www\mmr-final\admin\all_hospital_list.php on line 97

Notice: Undefined index: cHospital2 in F:\wamp\www\mmr-final\admin\all_hospital_list.php on line 98

Notice: Undefined index: cHospital1 in F:\wamp\www\mmr-final\admin\all_hospital_list.php on line 97

Notice: Undefined index: cHospital2 in F:\wamp\www\mmr-final\admin\all_hospital_list.php on line 98

Notice: Undefined index: cHospital1 in F:\wamp\www\mmr-final\admin\all_hospital_list.php on line 97

Notice: Undefined index: cHospital2 in F:\wamp\www\mmr-final\admin\all_hospital_list.php on line 98

Notice: Undefined index: cHospital1 in F:\wamp\www\mmr-final\admin\all_hospital_list.php on line 97

Notice: Undefined index: cHospital2 in F:\wamp\www\mmr-final\admin\all_hospital_list.php on line 98

Notice: Undefined index: cHospital1 in F:\wamp\www\mmr-final\admin\all_hospital_list.php on line 97

Notice: Undefined index: cHospital2 in F:\wamp\www\mmr-final\admin\all_hospital_list.php on line 98

Notice: Undefined index: cHospital1 in F:\wamp\www\mmr-final\admin\all_hospital_list.php on line 97

Notice: Undefined index: cHospital2 in F:\wamp\www\mmr-final\admin\all_hospital_list.php on line 98`

And also it's throwing Null row.

How can this query be changed to not cause an error?

Upvotes: 3

Views: 475

Answers (2)

John Conde
John Conde

Reputation: 219804

Those are not MySQL errors. They are PHP errors. Basically you are most likely attempting to use variables without declaring them first. Be sure to always declare your variables before using them. It makes you less like to have errors.

Upvotes: 2

Bill Karwin
Bill Karwin

Reputation: 562250

In a UNION query, the column names must be the same for all rows. So it uses the column names from the first query in the union. Column names in subsequent queries in the union are ignored.

In other words, in this query:

select id,cHospital from med_patient where cHospital is not null union 
select id,cHospital1 from med_patient where cHospital1 is not null union 
select id,cHospital2 from med_patient where cHospital2 is not null order by 1

The column names on all rows are: id and cHospital.

So in your PHP code, when you fetch the result as an object and try to reference a field of the object like this:

$cHospital1 = $row->cHospital1;
$cHospital2 = $row->cHospital2;

The object doesn't have fields by those names. It only has $row->cHospital, even for rows that came from the second and third queries in the union.

Upvotes: 0

Related Questions