I have a PHP page for displaying data from MySQL table 'table1'. I've added a simple visitors counter in the second PHP file, and it shows visits in another MYSQL table 'table2' in the same database.
I need to display data from 'table2' on the same PHP page where is data from 'table1'
Code for the PHP page.
<?php
$db_host = 'localhost'; // Server Name
$db_user = 'username'; // Username
$db_pass = 'password'; // Password
$db_name = 'database'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$sql = 'SELECT *
FROM table1 INNER JOIN table2';
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
Okay, so I did INNER JOIN to get both tables, but how to post visitors counter data from table2 in let's say h2 tag?
I don't really get your question right. But I think what you are doing wrong is your inner join.
Your INNER JOIN:
$sql = 'SELECT *
FROM table1 INNER JOIN table2';
How it should be:
$sql - 'SELECT * FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name';
Where the column names must have the same value.
I don't know how your tables are linked together.
JOIN is used to link a table to another on an attribute (like foreign key). You need to specify which attribute writing "SELECT * FROM table1 JOIN table2 ON table1.firstattribute = table2.secondattribute" that is equivalent to "SELECT * FROM table1, table2 WHERE table1.firstattribute = table2.secondattribute".
I think you need simply do a query on table2 filtering an attribute given from the first table1. You can do 2 queries or just one with JOIN. I'd like to have more information but here a sample
<?php
$db_host = 'localhost'; // Server Name
$db_user = 'username'; // Username
$db_pass = 'password'; // Password
$db_name = 'database'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$sql = 'SELECT *
FROM table1 JOIN table2 ON table1.attr1 = table2.attr2';
$query = $conn->query($sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
if(mysqli_num_rows($query)>0){
//we can create an object that has the same attribute of both tables
$object = $query->fetch_object();
//for example $object has views of table2.views
echo '<h2>Views:' . $object->views . '</h2>';
}
?>
So, if I understood good you only need use fetch_object and a correct form of JOIN
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.