count rows with same id and print - php

So I have this table 'users_photos'. It contains 38k rows with user pictures. Every row contains id, userid and link to the photo. So if a user have 3 pictures, that user id will show in 3 rows in the database.
What I want to do is count the number of users with 1 picture in the database, 2 pictures in the database etc.
UPDATE: I have now the following code
$sql = $mysqli->query("SELECT count(*), count_users from (SELECT u_id, count(*) as count_users FROM users_photos group by u_id) temp group by count_users");
$sql->data_seek(0);
while ($row = $sql->fetch_assoc()) {
echo "".$fetch." = " . $row['count_users'] . "\n<br>";
}
This prints the users that have 1 picture and up to 8. Not how many but only shows that in the database there is users that have 1 picture, 2 pictures etc. Now I need to figure out how to print the total users that have 1 picture etc.
Anyone have any tips? thanks on behalf!

Update Your Query With This
$sql = $mysqli->query("SELECT count(*),u_id as 'count_users' FROM users_photos group by u_id");

Sql Query:
$sql = $mysqli->query("SELECT count(*),u_id as 'count_users' FROM users_photos group by u_id");
You Can Print like this
// After Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT count(*),u_id as 'count_users' FROM users_photos group by u_id";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - count_users" . $row["count_users"]. "<br>";
}
} else {
echo "0 results";
}

You can do something like this:
$con = mysqli_connect("localhost","my_user","my_password","my_db");
$sql = 'SELECT u_id, count(*) AS count_users FROM users_photos GROUP BY u_id';
$result = mysqli_query($con, $sql);
while ($row=mysqli_fetch_assoc($result)) {
echo 'User id: ' . $row['u_id'] . ' Count: ' . $row['count_users'] . '<br>';
}
Keep in mind this is just a basic example. In a real world application there is more to do such as checking for errors.

Related

2 tables, 3 columns need 1 value

I am trying to get 5 bits of data, 5 of them come from tbl_playerstats
these columns are
StatsID
Score
Kills
Deaths
Rank
What im struggling with it that StatsID is linked to another table called tbl_playerdata
In this table the PlayerID is the same as StatsID their values are numeric, also in this tbl_playerdata is SoldierName which is what im am trying to put in place of StatsID , end goal being that only these show:
SoldierName
Score
Kills
Deaths
Rank
My code so far looks like this ( minus database connection details
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT StatsID, Score, Kills, Deaths, Rounds FROM tbl_playerstats Limit 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> Soldier: ". $row["StatsID"]. "<p> Score: ". $row["Score"]. "<p> Kills: ". $row["Kills"]. " <p>Deaths: " . $row["Deaths"] . $row["Rounds"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
I have googled and it looks like using a JOIN is the way to go, the examples that I have found haven't worked for me, this could be down to not really knowing what this is called I'm trying to do.
Join both tables using StatsID and PlayerID
<?php
$sql = "SELECT tps.*, tpd.* FROM tbl_playerstats tps, tbl_playerdata tpd WHERE tps.StatsID = tpd.PlayerID Limit 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<br> Soldier: ". $row["SoldierName"]. "<p> Score: ". $row["Score"]. "<p> Kills: ". $row["Kills"]. " <p>Deaths: " . $row["Deaths"] . $row["Rounds"] . "<br>";
}
} else {
echo "0 results";
}?>
Hi as your questions is not much clear and also the output is also not much cleared, what you want?
anyway, you can join two tables to get the common columns from those tables like below.
suppose table-1 is player have 5 columns
stats
score
kill
death
rank
and another tabel 2 is playerData having these columns
playerId
playerName
playerEmail
and so on...!!
and you want whole data of table 1 along with the playerEmail, and statId and Playerid is common. then use this query
select p.stats, p.score, p.kill, p.death, p.rank, d.playerEmail
from Player p
inner join playerData d
on p.statid = d.playerid.
try this if your tbl_playerstats main table then use left join with condition tps.StatsID = tpd.StatsID , hope it will help you
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT tpd.SoldierName,tps.Score,tps.Kills,tps.Deaths,tps.Rank FROM tbl_playerstats tps LEFT JOIN tbl_playerdata tpd on tps.StatsID = tpd.StatsID Limit 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> SoldierName: ". $row["SoldierName"]. "<p> Score: ". $row["Score"]. "<p> Kills: ". $row["Kills"]. " <p>Deaths: " . $row["Deaths"] . $row["Rank"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
and if you want to same data then use innner join
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT tpd.SoldierName,tps.Score,tps.Kills,tps.Deaths,tps.Rank FROM tbl_playerstats tps, tbl_playerdata tpd WHERE tps.StatsID = tpd.PlayerID Limit 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> SoldierName: ". $row["SoldierName"]. "<p> Score: ". $row["Score"]. "<p> Kills: ". $row["Kills"]. " <p>Deaths: " . $row["Deaths"] . $row["Rank"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
if you face any problem then inform me. i will try to help you

PHP Run query on SHOW TABLES results

How do I go about running a query on tables from a previous SHOW TABLES query? What I'm trying to do is create a PHP script that runs every 24 hours that sorts a table by "verified" descending and "votes" descending and update "nomnom" on the top result, for every table in the database.
$result = $conn->query("SHOW TABLES");
if($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$sql = "SET #clan = (SELECT clan FROM " . $row[0] . " ORDER BY verified DESC, votes DESC LIMIT 1); UPDATE " . $row[0] . " SET nomnom=0 verified=0; UPDATE " . $row[0] . " SET nomnom=1 WHERE clan=#clan";
$conn->query($sql);
echo $row[0] . ' done<br>';
}
} else {
echo 'query 0';
}
This correctly echos every table name followed by done, but isn't actually updating the tables. What am I missing?
UPDATE
So I've determined that the following should work:
$sql = "SET #clan := (SELECT `clan` FROM " . $row[0] . " ORDER BY `verified` DESC, `votes` DESC LIMIT 1); UPDATE " . $row[0] . " SET `nomnom`=0, `verified`=0; UPDATE " . $row[0] . " SET `nomnom`=1 WHERE `clan`=#clan";
by echoing $sql and running the queries returned through phpmyadmin without changing anything.
Here's a line that is echoed.
SET #clan := (SELECT clan FROM aerngardh ORDER BY verified DESC, votes DESC LIMIT 1); UPDATE aerngardh SET nomnom=0, verified=0; UPDATE aerngardh SET nomnom=1 WHERE clan=#clan
It just for some reason isn't actually doing it when using
$conn->query($sql);
UPDATE 2
Figured out a way to make it work. Would mark my answer but I can't for 2 days...
Try this query
$sql = SET #clan := (SELECT clan FROM aerngardh ORDER BY verified DESC, votes DESC LIMIT 1); UPDATE aerngardh SET nomnom=0, verified=0; UPDATE aerngardh SET nomnom=1 WHERE clan=#clan
This should work
Had to split the query into 3 separate queries. Full working code:
$conn = new MySQLi($servername, $username, $password, $dbname);
$result = $conn->query("SHOW TABLES");
if($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$sql = "SET #clan := (SELECT clan FROM " . $row[0] . " ORDER BY verified DESC, votes DESC LIMIT 1);";
$sql2 = "UPDATE " . $row[0] . " SET nomnom=0, verified=0;";
$sql3 = "UPDATE " . $row[0] . " SET nomnom=1 WHERE clan=#clan";
$conn->query($sql);
echo $conn->error . '<br>';
$conn->query($sql2);
echo $conn->error . '<br>';
$conn->query($sql3);
echo $conn->error . '<br>';
}
} else {
echo 'query 0';
}
If anyone would like to post how to make this a proper multi_query without getting queries out of sync errors, be my guest. I cba doing that lol.

I want to use two where conditions in php to get data from mysql

My problem is this:
<?php
// Connect to database server
mysql_connect("localhost", "root", "abcabc") or die (mysql_error ());
// Select database
mysql_select_db('iite') or die(mysql_error());
// Get data from the database depending on the value of the id in the URL
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"];
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Write the data of the person
echo'<h1>'. $row['title'].'</h1>';
echo'<h1>'. $row['price'].'</h1>';
}
// Close the database connection
mysql_close();
?>
I want to show related posts, for this I need to insert this:
$sql = "SELECT * FROM table1 where title like '%keyword%' limit 5";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["price"]. " " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
so how can I insert the related post part near
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"];
and how to echo?
Thanks
You can use OR or AND for combining different where conditions(according to requirement) in query :
Ex;
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"] ." OR title like '%keyword%' limit 5";
$strSQL = mysql_query(SELECT * FROM table1 WHERE id=" . $_GET["id"] ." OR title like '%keyword%' limit 5) or die(mysql_error());
$row_strSQL = mysql_fetch_assoc($strSQL );
$totalRows_strSQL = mysql_num_rows($strSQL );
if ($result->totalRows_strSQL > 0) {
// output data of each row
while($row_strSQL= $result->fetch_assoc()) {
echo "id: " . $row_strSQL["id"]. " - Name: " . $row_strSQL["price"]. " " . $row_strSQL["title"]. "<br>";
}
} else {
echo "0 results";
}
You don't need two seperate queries for that at all. Just use the OR operator in ur where clause like Where id=" . $_GET['id']." or title like '%keyword%'

if statement to check if mysql row exists, then selecting next query

I'm attempting to select a query to use based on the number of rows returned by a test result.
$id = mysql_real_escape_string(htmlspecialchars($_POST['id']));
$result = "SELECT FROM Notifications WHERE UserID=$id";
$r = e_mysql_query($result);
$row = mysql_fetch_array($r);
$num_results = mysql_num_rows($result);
$result = '';
if ($num_results != 0) {
$result =
"SELECT U.UserID,U.FirstName,U.LastName, " .
" DATE_FORMAT(U.BirthDate,'%m-%d-%Y') AS BirthDate, " .
" N.Email, N.Phone,N.ProviderName, N.SubNotifications " .
" FROM Users U, Notifications N " .
" WHERE U.LocationID=0 " .
" AND N.UserID='$id'";
} else {
$result =
"SELECT UserID, FirstName, LastName," .
" DATE_FORMAT(BirthDate, '%m-%d-%Y') AS BirthDate " .
" FROM Users " .
" WHERE LocationID = 0 " .
" AND UserID ='$id'";
}
echo $result;
e_mysql_result($result); //Bastardized/homegrown PDO
if ($row = mysql_fetch_assoc($result)) {
$retValue['userInfo'] = $row;
...
I'm checking the Notifications table to see if the UserID exists there, if it doesn't it loads what does exist from the Users table, if it does, then it loads everything from the Notifications table.
I'm echoing out the $result and the proper statement is loaded, but it doesn't execute. When I run the concatenated query I get from the PHP preview, it returns just fine.
Before I had to if/else this, I was running the first query, loading everything from the Notifications table, and it was loading just fine. What am I missing?
You can do the whole thing with one query with a LEFT JOIN.
$query= "SELECT U.UserID, U.FirstName,U.LastName, " .
" DATE_FORMAT(U.BirthDate,'%m-%d-%Y') AS BirthDate, " .
" N.Email, N.Phone,N.ProviderName, N.SubNotifications " .
" FROM Users U " .
" LEFT JOIN Notifications N " .
" ON U.UserID = N.UserID " .
" WHERE U.UserID = '$id'";
You are missing execute a query with mysql_query() on all $result
Also change (query variable should be quoted) so change your all variables $id quoted
$result = "SELECT FROM Notifications WHERE UserID=$id";
to
$result = "SELECT FROM Notifications WHERE UserID='$id'";
$r = mysql_query($result);
Note :- mysql_* has been deprecated use mysqli_* or PDO

mysql_fetch_array how to display a single value of a column

I have the query fetching 8 rows, I want to be able access the result by single column not the whole row. For example I want to display the Deviceid from row number 7. i can display all of the values of the column but I'm having trouble figuring out how to get just one value. I'm new to PHP so bear with me and thank you for any help.
This the code:
<?php
$con = mysql_connect("uimcswpro", "testmysql", "test123") or die('Could not connect to server');
mysql_select_db("storage", $con) or die('Sorry, could not connect to the database');
$query = "Select distinct a.Deviceid as Deviceid, c.Time as Time, b.devicehostname as devicehostname, ElementName, PoolID,
TotalManagedSpace, RemainingManagedSpace,
TotalDiskCapacity, HotspareCapacity, UnassignedStorageCapacity,
AssignedStorageCapacity
from tt_cim_storage_pool a, devices b, ent_san_storage_current c
where a.Deviceid = b.Deviceid
and (type = 'Unified Pool' or type = 'RAID Group' or type is NULL)
and c.time = (select max(c.Time) from tt_cim_storage_pool where deviceid=
(select deviceid from devices where devicehostname='UIH_8100_L14' and retire=0))
and devicehostname='UIH_8100_L14';";
$result = mysql_query($query,$con);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
echo "<br/>";
while ($row=mysql_fetch_array($result)) {
echo $row[0]. " - ".$row[1]. " - ".$row['devicehostname']. " - ".$row['ElementName']. " - ".$row['PoolID']
. " - ".$row['TotalDiskCapacity'];
echo "<br/>";
}
mysql_close($con);
?>
You can select desired row via sql using LIMIT keyword, or simple checking number of current row:
$rowNo = 0;
while ($row=mysql_fetch_array($result)) {
$rowNo++;
if ($rowNo == 7) {
echo $row[0]. " - ".$row[1]. " - ".$row['devicehostname']. " - ".$row['ElementName']. " - ".$row['PoolID']
. " - ".$row['TotalDiskCapacity'];
echo "<br/>";
}
}
You should also consider using modern database interface like mysqli

Categories