Add MySQL Count Column to PHP/HTML Table - php

I'm developing a website using HTML, PHP and MySQL to access a database. On one page I present a table with data from that database. This is some of the code I'm using:
$sql1 = "SELECT * FROM MyTable ORDER BY ID ASC";
$rs1 = mysqli_query($link,$sql1);
(...)
while($row1 = mysqli_fetch_assoc($rs1)) {
echo "<tr><td>".$row1['ID']."</td><td>".$row1['Field1']."</td><td></td><td>".$row1['Field2']."</td><td>".$row1['Field3']."</td></tr>\n" ;
}
Notice the empty <td></td>? That's because I want to have there the number of time a given ID appears on two other tables (there are foreign keys involved, obviously). I have sorted out the code I need for that:
$sql2 = "SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total";
However, I'm struggling with figuring out a way to add this result to the other table. Any help?

try with this.. it inserts the total to an table after selecting the count.
"INSERT INTO total_table (total)
SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total
WHERE cid = 2"

Related

Delete duplicate rows in MySQL using PHP script

I need a PHP function that deletes duplicate rows from MySQL database table. For example, I have a table like this:
I tried the following without success:
$find = mysql_query("SELECT * FROM users");
while ($row = mysql_fetch_assoc($find))
{
$find_1 = mysql_query("SELECT * FROM users ");
if (mysql_num_rows($find_1) > 0) {
mysql_query("DELETE FROM users WHERE ID =$row[num]");
}
I need to delete this duplicate rows and Keep only one of them only using PHP (and not my SQL database). Is there a way to do this?
You can do this with a single query, without a php loop (which, obviously, does not do what you want here):
delete t
from mytable t
inner join (select user, min(num) num from mytable group by user) t1
on t.user = t1.user and t.num > t1.num
This deletes rows that have the same user, while retaining the row with the smallest num.

Fetching data with Group by, How to select the latest or greatest id? (PHP to MySQL)

I wanted to fetch data from MySQL with PHP when a user inputs something. I have this code.
$query = "SELECT * FROM mealplans WHERE plantitle LIKE '%$inputText%' AND `STATUS` = 1 OR plantitle LIKE '%$inputText%' AND userid = '$userid' GROUP BY plantitle, userid";
$result = mysqli_query($con, $query);
It works fine however, it fetches the oldest or first data from the group. How do I select the newest data?
I've search and found possible solutions by using FROM, JOIN, IN, etc. However, I do not know how to use them since I only know the basics. Hopefully someone could explain one solution for me.
There is a simple solution that you can do.
You can order your data to DESC order. I'm sure that you have an id(primary key) in your table.You just have to order all your datas' to DESC order of ids .So that your last inserted data set will be the one to be fetched since it's on the top.
change your query to: (add your primary key(in the following query i have added it as id) in the ORDER BY syntax)
$query = "SELECT * FROM mealplans WHERE plantitle LIKE '%$inputText%' AND `STATUS` = 1 OR plantitle LIKE '%$inputText%' AND userid = '$userid' GROUP BY plantitle, userid ORDER BY `ID` DESC"
Just add a condition in your query which only retrieves the row having the greatest id.
Find out the id first and then you can use the same query for that id:
SELECT MAX(id) FROM mealplans WHERE plantitle LIKE '%$inputText%' AND `STATUS` = 1 OR plantitle LIKE '%$inputText%' AND userid = '$userid' GROUP BY plantitle, userid
After getting the id and storing it in a variable (say $temp):
SELECT * from mealplans where `id` = $temp

How to assign two SELECT queries results to single array variable($row)?

There are two queries with same fields names but different tables. I want fetch both select query's results in same array variable $result. I tried few things but nothing working for me. May b my bad day.
two table, need to be fetch in same variable $result.
$sql1="SELECT city,phone,name from table1 where city='NY'";
$result = $conn->query($sql1);
$sql2="SELECT city,phone,name from table2 where city='NY'";
$result = $conn->query($sql2);
I don't want $result lost $sql1 data after assigning same variable ($result) to second query. Please help
You can use UNION and along with that table record identifier to identify table records differently.
$sql1 = "(SELECT city,phone,name, 't1' ttype from table1 where city='NY')
UNION (SELECT city,phone,name,'t2' ttype from table2 where city='NY')";
$result = $conn->query($sql1);
Note: MySQL uses the DISTINCT clause as default when executing UNION queries if nothing is specified.
If you want duplicate records too, then use UNION ALL.
$sql1="SELECT city,phone,name from table1 where city='NY'
UNION
SELECT city,phone,name from table2 where city='NY'";
$result = $conn->query($sql1);

pull data from two tables with one query/ select statement

I am pulling one column from the USERS table but now I wanna pull columns from the MONEY table. How do I accomplish this?
sample database
USERS TABLE
userID = 33
nestEgg = 600000
MONEY TABLE
userID = 33
monthlyContributions = 500, 250, 300
totalContributions =
<?php
include 'inc/connect.php';
$query = "SELECT * FROM USERS WHERE userID = '$userID'";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_assoc($result);
?>
If I'm not mistaken, you're asking to create a column in MONEY which is the sum of nestEgg and monthlyContributions. I'm a total newbie, but I think getting the sum, followed by the insert, should look like:
SELECT (SELECT SUM(nestEgg) FROM USERS) + (SELECT SUM(monthlyContributions) FROM MONEY)
INSERT INTO MONEY(totalContributions)
If you only want the sum from the monthly contributions, then it should just be:
SELECT SUM(monthlyContributions) FROM MONEY
INSERT INTO MONEY(totalContributions)
If I'm not mistaken.

Getting Different ID Values in one table with DISTINCT query

My table in the DB
As you can see i have a table contain several IDs including Survey_survey ID and Store ID, i want to get all the Store IDs and their Survey_surveyIDs without duplicates.
Here is what i have tried
$getSurvey = mysqli_query($dbConnection , "SELECT DISTINCT Survey_surveyId FROM maintable");
while ($row = mysqli_fetch_array($getSurvey)) {
$getStoreIDS = mysqli_query($dbConnection , "SELECT DISTINCT Stores_storeID FROM maintable WHERE Survey_surveyId=".$row['Survey_surveyId']."");

Categories