I want to search in two tables. Tried this but didn't worked. I'm getting error "Unkown Column...."
HTML:
<form method="post"
<input type="text" name="search_keyword">
<input type="submit" name="button_search">
</form>
MYSQL SELECT AND PHP:
if(isset($_POST['button_search']))
{
$search_keyword = $_POST['search_keyword'];
$select = mysql_query("SELECT * from table_1 WHERE match(name_1) against ($search_keyword)
union all SELECT * from table_2 WHERE match(name_2) against ($search_keyword)");
while($row = mysql_fetch_array($select))
{
echo $row['question'];
echo $row['category_name'];
}
}
TABLES:
For example:
Table 1:
table name: table_1
Values (table 1):
+-------+-------------+
| id_1 | name_1 |
+-------+-------------+
| 1 | Phinoy |
| 2 | Go |
+-------+-------------+
Table 2:
table name: table_2
Values:
+-------+-------------+
| id_2 | name_2 |
+-------+-------------+
| 1 | Gi |
| 2 | Phinas |
+-------+-------------+
If I search "P" or "Ph" , it will show the values "Phinoy and Phinas".
Well. First you need is use an INNER JOIN for comparing two tables at the same time. In this code, we are concatening the result of the table 1 and the table 2, then we are calling the table_1 and with a INNER JOIN we will compare the table_2 if in the table_1 there are any result LIKE table_2 and only just happening in the column name_1 and name_2.
<?php
$query = "SELECT
CONCAT(table_1.name_1,' and ',table_2.name_2)
FROM table_1 INNER JOIN table_2
ON table_1.name_1 LIKE table_2.name_2";
mysql_query($query);
?>
Related
I am currently populating a data table on my website from information stored in a mysql database
The table is of the form:
Table 1
ID | DataA | Other Info | Count Data
======================================
1 | A | Other Info | 2
2 | B | Other Info | 3
Table 2
ID | Input
==========
1 | A
2 | A
3 | B
4 | B
5 | B
Count data in table 1 is intended to show how often the entry form the DataA column appears in the input column in Table2
Update....
CREATE TABLE driver (
`ID` INTEGER,
`DataA` VARCHAR(1),
`Other Info` VARCHAR(10),
primary key (ID)
);
$sql = "SELECT * FROM `driver` ORDER BY drivercompany";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
// output data of each row
while ($result = mysqli_fetch_assoc($query)) {
echo "<tr>
<td class='class'>" . $result['id'] . "</td>
<td>" . $result['DataA'] . "</td>
<td>" . $result['otherinfo'] . "</td>
<td></td> /**count goes here**/
</tr>";
}
}
?>
using db fiddle, the query I need to get the count is:
SELECT driver.*, COUNT(add_job.Input) AS counter
FROM driver
LEFT JOIN add_job ON add_job.Input = driver.DataA
GROUP BY driver.ID
I have tried adding it to my code as so:
$sql = "SELECT * FROM `driver` ORDER BY drivercompany";
$query = mysqli_query($conn, $sql);
$count = "SELECT `driver`.*, COUNT(`add_job`.`adddriver`) AS counter
FROM `driver`
LEFT JOIN `add_job` ON `add_job`.`adddriver` = `driver`.`drivercompany`
GROUP BY `driver`.`id`";
$counter = mysqli_query($conn, $count);
while($result = mysqli_fetch_assoc($query,$counter)) { //and other variations
I cannot determine how to get $count and $query to work together
You can JOIN the two tables, group by the primary key of table1 and count the number of occurances in table2 with a single query.
Assuming ID is the primary key in table1, change your query to:
$sql = "
SELECT t1.*, COUNT(t2.Input) AS counter
FROM table1 t1
LEFT JOIN table2 t2 ON t2.Input = t1.DataA
GROUP BY t1.ID
";
The result would be:
| ID | DataA | Other Info | Count Data | counter |
| --- | ----- | ---------- | ---------- | ------- |
| 1 | A | Other Info | 2 | 2 |
| 2 | B | Other Info | 3 | 3 |
See the result in db-fiddle
Then you can use $result['counter'] in your output. Eg.:
echo "
<tr>
<td class='class'>{$result['id']}</td>
<td>{$result['DataA']}</td>
<td>{$result['otherinfo']}</td>
<td>{$result['counter']}</td>
</tr>
";
Note: If you have the ONLY_FULL_GROUP_BY mode enabled in MySQL < 5.7 or any version of MariaDB, the query will raise an error. In this case you should change it to
SELECT t1.id, t1.DataA, t1.otherinfo, COUNT(t2.Input) AS counter
FROM table1 t1
LEFT JOIN table2 t2 ON t2.Input = t1.DataA
GROUP BY t1.id, t1.DataA, t1.otherinfo
To include all selected non-aggreagted columns in the GROUP BY clause.
I have this 2 tables:
+---------------+--------+
| id1 | name |
+---------------+--------+
| 1 | test |
| 2 | teest |
| 3 | teeest |
+---------------+--------+
+-----+------------+---------+-----------+---------+
| id2 | date | morning | afternoon | evening |
+-----+------------+---------+-----------+---------+
| 1 | 2017-12-14 | 1 | 2 | 1 |
| 2 | 2017-12-15 | 2 | 1 | 3 |
+-----+------------+---------+-----------+---------+
All I want to do is to echo, in a php file, the values of the second table but instead of numbers I want to echo the names of the first table in their place.
Can someone teach me how to take this result?
Edit: When i use this code:
<?php
$sql = mysqli_query($con, "SELECT * FROM table2");
while ($row = mysqli_fetch_array($sql)) {
echo "<center>" . $row['date'] . " " .$row['morning']. " " .$row['afternoon']. " " .$row['evening']. "</center>";
}
?>
i have the result
2017-12-14 1 2 1
2017-12-15 2 1 3
and i want this instead:
2017-12-14 test teest test
2017-12-15 teest test teeest
Thanks.
You should use JOIN.
Query
select
`t2`.`id2`,
`t2`.`date`,
`ta1`.`name` as `morning`,
`ta2`.`name` as `afternoon`,
`ta3`.`name` as `evening`
from `table2` as `t2`
join `table1` as `ta1`
on `ta1`.`id1` = `t2`.`morning`
join `table1` as `ta2`
on `ta2`.`id1` = `t2`.`afternoon`
join `table1` as `ta3`
on `ta3`.`id1` = `t2`.`evening`;
Fiddle demo
Select the values from the first table into an array and when presenting the second table, use the values of the second table as keys.
Sample:
$names = [1 => 'test', 2 => 'teest', 3 => 'teeest'];
echo $names[$secondrow["morning"]];
If I understand correctly...
The best is to have those table with INNODB engine with relation between tables, ie foreign key defined between second table to the first table.
Then you will run SQL query to database using the relation you will receive data from both tables and in the SELECT part of the query you define what columns to be shown.
SELECT atable.name, btable.*
FROM btable
JOIN atable ON btable.name_id = atable.id;
Here is my example: http://sqlfiddle.com/#!9/e851e0/3
my data there will be a number key how to equalize with another table so it can be called names. i want to changes data (number key) to text from other table.
my table1 :
+-----------------------+
| ID | Name | Category |
-------------------------
| 1 | Home | 21 |
| 2 | Pro | 23 |
+-----------------------+
and table 2 :
+---------------------+
| ID | name_category |
-----------------------
| 21 | Sweet Home |
| 23 | your Home |
+---------------------+
how to get the same ID?. but the data will be shown in table 1
Try like this.Use join on table1.ID = table2.ID.displays all data of table1 with category names from table2 matching on table1 category ID.
$this->db->select(*)
->from('table1')
->join('table2', 'table1.ID = table2.ID');
$result = $this->db->get()->result_array();
print_r($result);//displays all data of table1 with category names from table2 matching on table1 category ID.
$this->db->query('select table1.* from table1 inner join table2 on table1.id = table2.id');
$this->db->result();
I have two tables in mysql db.Table_1 and Table_2 I am displaying the whole table in HTML using the following code :
<table>
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "database";
$results = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM Table_1");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$results = $stmt->fetchAll();
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
<table>
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php foreach($results as $key=>$row) { ?>
<tr>
<td><?php echo $row['Name'];?></td>
<td><?php echo $row['Address'];?></td>
<td><?php echo $row['Email'];?></td>
</tr>
<?php } ?>
</tbody>
</table>
</table>
Now i want to add one more column to this HTML table where the data will be coming from Table_2.In this Table_2 there will be multiple comments inserted for a single post in Table_1.
Iam querying the latest comment for the post using the query statement :
SELECT comment FROM Table_2 WHERE id = (SELECT id
FROM Table_2 WHERE post_id = 10 ORDER BY id DESC LIMIT 1)
Here we are specifying the post_id = 10 but when iam usiong SELECT * FROM Table_1" to display all the data from table_1 how should i specify to display a latest comment for that particular post in table_2
Table-1 Structure:
+-------+---------+---------+---------+
| id | Name | Address | Email |
+-------+---------+---------+---------+
| 1 | ABC | ABC | ABC |
| 2 | DEF | DEF | DEF |
+-------+---------+---------+---------+
Table-2 Structure:
+-------+-------------+---------+
| id | Table_1_id | Comments|
+-------+-------------+---------+
| 1 | 1 | X |
| 2 | 1 | Y |
| 3 | 2 | Z |
+-------+-------------+---------+
HTML to be displayed:
+---------+---------+---------+---------+
| Name | Address | Email | Comments|
+---------+---------+---------+---------+
| ABC | ABC | ABC | Y |
| DEF | DEF | DEF | Z |
+---------+---------+---------+---------+
Thanks in advance.
If you want to get all the posts along with its latest comment then you can use the following query :
SELECT
Name,
Address,
Email,
finalTable.comment
FROM
Table_1
INNER JOIN
(
SELECT
comment,
Table_1_id
FROM Table_2
INNER JOIN
( SELECT
MAX(id) latest_comment_id
FROM Table_2
GROUP BY Table_1_id ) latestComments
ON Table_2.id = latestComments.latest_comment_id
) finalTable
ON finalTable.Table_1_id = Table_1.id;
It will give an output result like below:
+---------+---------+---------+---------+
| Name | Address | Email | Comments|
+---------+---------+---------+---------+
| ABC | ABC | ABC | Y |
| DEF | DEF | DEF | Z |
+---------+---------+---------+---------+
Note: If you want all the posts i mean those posts too which don't have any comment yet then replace the INNER JOIN by LEFT JOIN
Demo Here
you can use joins as below
select Table_1.*
from Table_1
left join Table_2 on
(Table_1.id=Table_2.Table_1_id)
and
Table_2.id>
(select id from Table_2
where Table_1_id='10'
order by id DESC LIMIT 2,1)
You can do this with MySql JOIN to retrieve data from multiple tables with the same query.
I see that you are using php PDO, you can use join like this:
$stmt = $conn->prepare(" SELECT Table1.*, Table_2.Comment FROM Table_2
LEFT JOIN Table_1 ON ( Table_2.Table_1_id=Table_1.id)
WHERE id = (SELECT id
FROM Table_2 WHERE post_id = 10 ORDER BY id DESC LIMIT 1)");
if ($stmt->execute(array($getVars['Comment']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
how to get table_1 id which is not in table_2
my table look like this type.
table_1
---------------------------------------------
| id | user |
---------------------------------------------
| 1 | Jack |
---------------------------------------------
| 2 | John |
---------------------------------------------
table_2
------------------------------------------
| web_id | website |
------------------------------------------
| 2 | Facebook |
------------------------------------------
| 3 | Google+ |
------------------------------------------
i want to codeigniter query
$this->db->select("*");
$this->db->from("table_1");
$this->db->where_not_in('id', "table_2.web_id");
return $this->db->get();
Try this
SELECT id
FROM table_1
WHERE id NOT IN
(
SELECT web_id FROM table_2 WHERE 1
);
Using CodeIgniter Active Records the query will be as follows
$this->db->select('*');
$this->db->where('id NOT IN (SELECT web_id FROM table_2 WHERE 1)', NULL, FALSE);
$query = $this->db->get('table_1');
Something like this would do it (depending on what flavour of SQL you're using you may have to adjust syntax slightly):
SELECT id
FROM table_1
WHERE id NOT IN (SELECT web_id FROM table_2)
However, I don't see what use this is. There's no identifiable link between the two tables, so knowing that there's an id of 1 in table_1 but no web_id of 1 in table_2 doesn't seem like a useful piece of information.
select t1.id
from table_1 t1
left join table_2 t2 on t1.id = t2.web_id
where t2.web_id is null