0

I am trying to allow users to search a database and echo results, the thing is I want to search multiple tables. I know I can do SELECT * FROM x1, x2 but the rows are named something else so I cant echo $row['username'] when the other row is username2. Maybe if its possible something like if($row == whatever), idk. Thanks for any help.

<?php
$search = $_POST['Srch'];
$host = "whatever";
$db = "whatever";
$user = "whatever";
$pwd = "whatever";
$link = mysqli_connect($host, $user, $pwd, $db);
$query = "SELECT * FROM users WHERE email LIKE '%$search%'";
$results = mysqli_query($link, $query);

if(isset($_POST['Srch'])) {
  if(mysqli_num_rows($results) >= 0) {
    while($row = mysqli_fetch_array($results)) {
        echo "Username: " . $row['username'];
        echo "Email: " . $row['email'];
    }
  }
}
?>
<body>
<form action="" method="POST">
<input type="Text" name="Srch">
<input type="Submit" name="Submit">
</form>

Edit: Found a way to do this. Something like this works:

function search1() {
// Search stuff here
}
function search2() {
// Search more stuff here
}

if(isset($_POST['Srch'])) {
search1();
search2();
}
james
  • 1
  • 1
  • 1
    Check out the Q&A http://stackoverflow.com/q/6574564/ and http://stackoverflow.com/q/16925584/ - Continue your Google search "search multiple tables mysql" – Funk Forty Niner Nov 27 '14 at 19:55
  • Never add user input into a query like that. Use prepared statements or at the least, escape the input. – Jite Nov 27 '14 at 19:55
  • @Jite Yeah I know, I wanted to get the search working then I would escape & trim the input. – james Nov 27 '14 at 20:06

1 Answers1

0

If you want to search multiple tables you're going to have to join them somehow. Since you didn't post your table structure, I can only make assumptions on what you're trying to do, but the general syntax would be:

$query = "SELECT * FROM users u LEFT JOIN something s ON s.id = u.something_id WHERE u.email LIKE '%$search%'";

Then you can echo out the different columns that return. But again, this question needs more information for a better answer.

Hope this helps anyway!

Tim Lewis
  • 27,813
  • 13
  • 73
  • 102