2

I have got two tables in MySQL database, I want to use php to search in them, which I am able to do. however the problem is coming when I want to display data from table in my website. Those two tables have different field names and different number of fields. Is there any possibility to display rows by index or something like that. thanks a lot for your help.

That's my code php code:

 <?php
//variables to connect to db
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "project";
$lookingto = $_POST["sendTo"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

//getting user details from data base
$sql = "SELECT * FROM ".$lookingto."";
$result = $conn->query($sql);

if ($result->num_rows > 0) {

    echo "<table><tr><th>Your search results</th></tr>";
    echo "<tr><td><h3>Name</h3></td><td><h3>ID</h3></td></tr><tr>";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<td>".$row["make"]."</td><td>".$row["model"]."</td></tr>";
        }
    echo "</table>";

} else {
    echo $lookingto;
    echo "No details found, please check your details and try again";
}
$conn->close();
?>
Shubhamoy
  • 3,718
  • 2
  • 19
  • 24
zygis089
  • 21
  • 1
  • 1
  • 2
  • 1
    You can use JOIN to get data from more than 1 table, can you please share table structure by which you want to get data. – Sachin Vairagi May 06 '16 at 10:22
  • Your SQL query is incomplete. (SELECT * FROM ".$lookingto."";) Is the user submitting the remaining query? – Shubhamoy May 06 '16 at 10:35

2 Answers2

3

Join Query :

Select * from Table1
LEFT JOIN Table2 on Table2.col1 = Table1.colb 
where Table1.cola = $var

Where $var is the id you are searching for and the two tables are linked by col1(of Table2) and colb(of Table1)

You may change the columns/tables & type of join as per your use case.

Which Join to use?

enter image description here

Source : Code Project - Visual Representation of SQL Joins

Community
  • 1
  • 1
Ani Menon
  • 27,209
  • 16
  • 105
  • 126
0

If there is any relation key used between two table then you can use join to get data using that foreign key.

E,g select table1.*, table2.* from table1 LEFT JOIN table2 on table2.col2=table1.col1 where table1.col=$variable