counting occurrences of certain inputs in data table/database - php

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.

Related

Get ID from one tabe and find name for that ID

In my data base I have 3 tables.
user (table name)
so many row are there one of the row name user and if
--------------------
| id | user |
--------------------
| 7 | user |
| 8 | user_name_2 |
| 11 | user_name_5 |
--------------------
and another table call data
----------------------------
| id | user-id | number |
----------------------------
| 1 | 7 | 789654125 |
| 2 | 8 | 465654545 |
| 3 | 11 | 884554511 |
----------------------------
In table td user_id is table user id
now I want to show name and number in php
$conn = mysqli_connect("localhost","root","QAZWS12","user");
$sql = "SELECT * FROM user"
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$id = $row["id"];
}
did the same and get $number = $row["number"]
Now I want is in data table user id auto get table user number how can i do that?
Final output
user 789654125
user_name_2 465654545 like that
You have to use join here. For more details on different types JOINS refer either official MySQL doc or search online
replace this query
$sql = "SELECT u.id,u.user AS user_name,d.number AS user_number
FROM user u LEFT JOIN description d ON u.id = d.user-id";
The above query will fetch user id and username and user number
replace this too
$id = $row["id"].' '.$row['user_name'].' '.$row['user_number'].'<br/>';
This outputs as
7 user 789654125
Try below SQL query with LEFT JOIN to get the username with their mobile number in the result set:
$sql = "SELECT u.user, d.number
FROM user as u
LEFT JOIN data as d ON d.user-id = u.id
"
user SQL Left join
$sql = "SELECT * FROM user LEFT JOIN call_data ON user.id = call_data.user-id";
while accessing data
$number = $row['number'];
learn about SQL JOINS TUTORIAL

mySQL: How to search in multiple tables in database?

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);
?>

Dispaly all the data from a mysql table with additional information from second table

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);
}
}

Delete consecutive duplicates from a table in mysql

I have a database , where table contains consecutive duplicate rows . Demo of table with data is as follows.
id name processed
1 xyz 0
2 xyz 0
3 ABC 0
4 ABC 0
I want to delete the consecutive duplicate from this table , and once duplicate is deleted update processed to 1. So that the final table looks like follows.
id name processed
1 xyz 1
3 ABC 1
I am doing it as follow.
SET #v1 := (select group_concat(`id`) from `names` as m1 where 0 < (select count(*) from `names` as m2 where m2.`id` = m1.`id` - 1 and m2.`name` = m1.`name`));
DELETE FROM names WHERE id IN (#v1);
UPDATE names SET `processed`=1 WHERE `processed`=0
The query works fine , but it deletes one row at a time . Please help me on this.I want all the selected rows to be deleted .
Thanks in advance.
As #MarkBaker already wrote in comment, you can try DELETE FROM table WHERE name=name and id>id.
But that's only fix to what already has been done. To prevent that, you should add unique index to name column. That should prevent any duplicates of being added in future.
You can't set unique index when you have duplicates though, so you need clean first :)
You cannot UPDATE and DELETE in the same query. So that pretty much leaves you with this:
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,name CHAR(3) NOT NULL,processed TINYINT NOT NULL DEFAULT 0);
INSERT INTO my_table VALUES
(1 ,'xyz', 0),
(2 ,'xyz', 0),
(3 ,'ABC', 0),
(4 ,'ABC', 0);
SELECT * FROM my_Table;
+----+------+-----------+
| id | name | processed |
+----+------+-----------+
| 1 | xyz | 0 |
| 2 | xyz | 0 |
| 3 | ABC | 0 |
| 4 | ABC | 0 |
+----+------+-----------+
SELECT y.* FROM my_table x JOIN my_table y ON y.id = x.id + 1 AND y.name = x.name;
+----+------+-----------+
| id | name | processed |
+----+------+-----------+
| 2 | xyz | 0 |
| 4 | ABC | 0 |
+----+------+-----------+
DELETE y FROM my_table x JOIN my_table y ON y.id = x.id + 1 AND y.name = x.name;
Query OK, 2 rows affected (0.00 sec)
UPDATE my_table SET processed = 1;
Query OK, 2 rows affected (0.00 sec)
SELECT * FROM my_table;
+----+------+-----------+
| id | name | processed |
+----+------+-----------+
| 1 | xyz | 1 |
| 3 | ABC | 1 |
+----+------+-----------+
For PHP and MySQL, If your all data is consecutive pairs then this will work.
$con = mysqli_connect('host', 'user', 'pass', 'db');
$query ="select m1.id from names as m1 where 0 < (select count(*) from names as m2 where m2.id = m1.id - 1 and m2.name = m1.name)";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result)){
$query2 ="DELETE FROM names WHERE id = ".$row['id'];
mysqli_query($con, $query2);
$id = $row['id']-1;
$query3 ="UPDATE names SET `processed`=1 WHERE id = ".$id;
mysqli_query($con, $query3);
}
I checked it and its working fine. Hope it works for you too.
This will not edit your table, but will give you SELECT with desired result:
SELECT min(id) id, name, 1 processed
FROM mytable
GROUP BY name
You can use this in CREATE TABLE newtable AS SELECT ..., and then DROP mytable, and finally to ALTER TABLE newtable RENAME TO mytable.
The DISTINCT keyword can be used to return only distinct (different) values.
Use this query:
SELECT DISTINCT `id`, `name`,`1` AS processed
FROM mytable;

PHP SQL Query That Displays Certain Results Based On Values In Another Table

Right now, I have two database tables. Table history_2014 has a column(member) that says whether or not a member is active (Y or N). I have another table called history_overall that contains all of the contact information for these members. I need a table that will only show the rows of history_overall for active members. Right now, I have this PHP:
<?php
$con=mysqli_connect("localhost","myusername","mypassword","mydatabase");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM history_overall");
echo "<table border='1'>
<tr>
<th>Address 1</th>
<th>Last Name</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['address1'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The current code will allow me to display all rows, but I need to be able to display certain rows based on the other table.
what column ties the two tables together?
A JOIN will accomplish this if there is a relationship.
Example:
SELECT history_overall.* FROM members
JOIN history_overall
ON history_overall.member_id = members.id
WHERE members.active = 'Y';
----Edit/Comment----
Since I'm not able to add the table structure layout in a comment I will comment here.
It is more valuable when wanting to retrieve specific records from the database to provide us with the table schema as opposed to the actual table names. As well as an example of the resulting data you want as a result.
All you really provided to us with is table history_2014 with columns (member = Y|N), table history_overall with columns (address1, last_name) which doesn't allow us to build a relationship between the two (or more) tables.
Here is an example assuming both tables have a memberid column:
----------------------- -------------------------------------
| table1 | | table2 |
----------------------- -------------------------------------
| member | memberid | | address1 | full_name | memberid |
----------------------- -------------------------------------
| Y | 1 | | 123 street | jon doe | 1 |
----------------------- -------------------------------------
| N | 2 | | 789 court | jane doe | 2 |
----------------------- -------------------------------------
| Y | 3 | | 456 road | foo bar | 3 |
----------------------- -------------------------------------
Question: How can I retrieve records from table2 where the member in table1 is 'Y'?
This is my desired result of the records:
-------------------------------------
| recordset |
-------------------------------------
| address1 | full_name | memberid |
-------------------------------------
| 123 street | jon doe | 1 |
-------------------------------------
| 456 road | foo bar | 3 |
-------------------------------------
Answer query:
SELECT table2.*
FROM table1
JOIN table2
ON table1.memberid = table2.memberid
WHERE table1.member = 'Y'
Explained:
Retrieve all columns in table2 that the memberid column in table1 is the same as the memberid column in table2 from the rows in table1 that the member column contains Y as a value with no ordering or limit on the amount of records returned.
I guess you have some kind of Id of the user in both tables, you could make a query creating a join between the two tables where id matches and selecting only the rows where member = 'Y'
Simply use this method
select * from history_overall,members where members.status='active'
You will get all the active members results including history also.
Use a table join (MySQL doc: http://dev.mysql.com/doc/refman/5.7/en/join.html).
In short, something like:
SELECT ho.*
FROM history_overall AS ho
RIGHT JOIN history_2014 AS h ON ho.memberId = h.memberId
WHERE h.isActive = 'Y';
Obviously your field names are probably different...

Categories