0

I am trying to make my php code to read off of two tables in my database. Like if it does not exist in one table it will check the other and see.

$mystyle = mysql_query("SELECT * FROM images WHERE `name` = '$name'"); 

How would I make it read from the table images and the table images_2

I tried doing this: [but didn't work of course]

$mystyle = mysql_query("SELECT * FROM images, images_2 WHERE `name` = '$name'"); 

3 Answers3

5

Use UNION(implicit distinct) or UNION ALL :

SELECT * FROM images WHERE `name` = '$name'
UNION ALL
SELECT * FROM images_2 WHERE `name` = '$name'

Assuming images and images_2 has the same table structure, otherwise you have to list the columns' names explicitly instead of SELECT *.


Note that: Use PDO instead of Mysql_* functions, it is deprecated and vulnerable to SQL Injection.

Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
  • Looks like Ive got alot more coding to learn :L Could you give me an example of my code ^ in PDO or Mysqli? – user2594383 Nov 06 '13 at 12:48
  • @user2594383 - There is a lot of tutorials in the web, see [**this**](http://www.phpeveryday.com/articles/PHP-Data-Object/PDO-Tutorial-P842.html), and [**this**](http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers) for example. – Mahmoud Gamal Nov 13 '13 at 02:22
0

I think you will have to return a count of the rows from the SELECT on images and if zero then run the SELECT against images_2

Mike
  • 2,391
  • 6
  • 33
  • 72
0

You can use UNION ,

(SELECT 1 AS sort_col, col1a, col1b, ... FROM t1)
 UNION
(SELECT 2, col2a, col2b, ... FROM t2) ORDER BY sort_col;

http://dev.mysql.com/doc/refman/5.0/en/union.html

Krish R
  • 22,583
  • 7
  • 50
  • 59