Solved

PHP/MySQL UNION statement question

Posted on 2011-09-08
3
288 Views
Last Modified: 2012-06-21
I am trying to use a union statement to select two values from two different tables. When i run it as an SQL it works fine but when I try to use it with php it only returns the first part of the query. here is the code below. I have also tried (statement a) UNION (statement b) like the description in the manual.  thanks for any help with this.

B
$query = "SELECT description FROM pages WHERE `page_id` = 'index' UNION SELECT age FROM names WHERE `name` = 'brian'";
$results = mysql_query($query);
$info = mysql_fetch_array($results);


$descrip = $info['description'];
$age = $info['age'];


echo $descrip . "-" . $age . "<br>";

Open in new window

0
Comment
Question by:jaxbrian
  • 2
3 Comments
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 500 total points
ID: 36504534
this is normal, because UNION will result in 2 rows, not "append" the columns.

you might want this:
query = "SELECT p.description , n.age FROM pages p, names n
WHERE p.`page_id` = 'index' and n.`name` = 'brian'";

$results = mysql_query($query);
$info = mysql_fetch_array($results);


$descrip = $info['description'];
$age = $info['age'];


echo $descrip . "-" . $age . "<br>";

Open in new window

0
 
LVL 2

Author Comment

by:jaxbrian
ID: 36504873
That worked, I have no idea why. lol. I am goign to read more on it now and see whats going on.

thank you for your help
0
 
LVL 2

Author Closing Comment

by:jaxbrian
ID: 36504876
thank you
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
When table data gets too large to manage or queries take too long to execute the solution is often to buy bigger hardware or assign more CPUs and memory resources to the machine to solve the problem. However, the best, cheapest and most effective so…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question