1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Php/mysql - query two tables?

Discussion in 'PHP' started by Sycrid, Feb 8, 2015.

  1. #1
    Hi Guys,

    I'm sure that this is really simple, but I just can't seem to get my head around the examples online.
    I have the following code.

    $sql = "SELECT * FROM `AssetHardware` WHERE `AssetTag` LIKE '%{$AssetSearchCriteria}%'";

    And what I want to do is, query two tables in the same database, and in those tables is the same column, so I want something similar to ...

    $sql = "SELECT * FROM `AssetHardware` AND 'AssetSoftware' WHERE `AssetTag` LIKE '%{$AssetSearchCriteria}%'";

    However this does not work. Can anyone help me, and explain the answer. Like I said I'm a bit puzzled by the explanations online.

    Thanks in advance for any help



     
    Solved! View solution.
    Sycrid, Feb 8, 2015 IP
  2. #2
    Hi

    You're on the right track but you have to tell the database how to join those tables together, if at all.

    Lets say that the two tables have the exact same columns - you could use a union

    $sql = "SELECT * FROM `AssetHardware` WHERE `AssetTag` LIKE '%{$AssetSearchCriteria}%'
    UNION
    SELECT * FROM 'AssetSoftware'  WHERE `AssetTag` LIKE '%{$AssetSearchCriteria}%'";
    PHP:
    If they don't have the exact same columns but the ones you want are the same then replace the * with the column names.
     
    sarahk, Feb 8, 2015 IP
  3. Sycrid

    Sycrid Well-Known Member

    Messages:
    130
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    128
    #3
    Hi SarahK,

    That was great help. I just struggled to comprehend how that works. I've fiddled with what you wrote to include my columns, as you mentioned and now it works.

    This is the final bit of code.
    $sql = "SELECT AssetTag, Name, Department FROM `AssetHardware` WHERE `AssetTag` LIKE '%{$AssetSearchCriteria}%'
    UNION
    SELECT AssetTag, Name, Department FROM `AssetSoftware` WHERE `AssetTag` LIKE '%{$AssetSearchCriteria}%'";
    
    PHP:
     
    Sycrid, Feb 10, 2015 IP
  4. sarahk

    sarahk iTamer Staff

    Messages:
    28,500
    Likes Received:
    4,460
    Best Answers:
    123
    Trophy Points:
    665