I'm working on a project where I have to show the leaderboard of players. But when wrote the below code, It shows the ranks with 2, 4, 6, 8, ... But not the odd numbered ranks. Can anyone tell me "What's wrong in this ?"
$query1_string = "CREATE VIEW Leaderboard AS SELECT Name, Points, PhoneNo
FROM user ORDER BY Points DESC";
$query2_string = "set #rank = 0";
$query3_string = "SELECT #rank := #rank + 1 as Rank, Name, Points
FROM Leaderboard";
$query5_string = "DROP VIEW Leaderboard";
// Doing the queries
$query1 = mysqli_query($con, $query1_string) or die(mysqli_error($con));
$query2 = mysqli_query($con, $query2_string) or die(mysqli_error($con));
$query3 = mysqli_query($con, $query3_string) or die(mysqli_error($con));
// Initializing the count
$count = 0;
//Making an array of strings including Rank, Name and Points of the Top 5 Players
while (($count < 5) && (mysqli_fetch_array($query3, MYSQL_NUM))) {
$row = mysqli_fetch_array($query3, MYSQL_NUM);
$results[$count] = $row[0] . " " . $row[1] . " " . $row[2];
$count++;
}
// Dropping the view.
$end_query = mysqli_query($con, $query5_string) or die(mysqli_error($con));
//Returning the array
$leader = implode("\n", $results);
echo $leader;
You are executing the query3 two times and displying the data retrieved from second execution
while (($count < 5) && (mysqli_fetch_array($query3, MYSQL_NUM))) {
$row = mysqli_fetch_array($query3, MYSQL_NUM);
Related
I need to save the count(activity_type) group by user_posted_to into a variable from mysql query
$query = "
SELECT user_posted_to, COUNT(*)
FROM activity_log_table
WHERE
post_type = 'discussion'
AND activity_type = 'Like' ";
$query .= "AND activity_timestamp >= CURRENT_DATE - INTERVAL 7 DAY AND activity_type <= CURRENT_DATE ";
$query .= "GROUP BY user_posted_to ORDER BY activity_timestamp DESC LIMIT 25";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
$user_posted_to = (int)$row['user_posted_to'];
$timestamp = time();
// I need to insert the count into this table for number_assert
$query2 = "INSERT INTO top_weekly (user_id, number_assert, timestamp) VALUES ($user_posted_to, $timestamp)";
$result2 = mysqli_query($connection, $query2);
$confirm_query2 = confirm_query($result2);
if($confirm_query2) {
echo "success query 2";
} else {
echo "failed query 2";
}
}
i expect to save the count() group by into a php variable and to be able to use it later on the page
You want to alias the « COUNT(*) » to something else, like « cnt ». Then you can access the column by name after fetching, as demonstrated below :
$query = "
SELECT
user_posted_to,
COUNT(*) as cnt
FROM activity_log_table
WHERE
post_type = 'discussion'
AND activity_type = 'Like'
AND activity_timestamp >= CURRENT_DATE - INTERVAL 7 DAY
AND activity_type <= CURRENT_DATE
GROUP BY user_posted_to
ORDER BY activity_timestamp DESC
LIMIT 25";
$result = mysqli_query($connection, $query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "user_posted_to: " . $row["user_posted_to"]. " - Count: " . $row["cnt"] . "<br>";
}
} else {
echo "0 results";
}
Add and AS label to the COUNT(*) then you will be able to readout that label in the row you get.
$query = "SELECT user_posted_to, COUNT(*) AS varCount FROM activity_log_table WHERE post_type = 'discussion' AND activity_type = 'Like' ";
$nummerOfCount = $row['varCount']
I want to delete some posts in a database, but for some rows, only if they are the only children with the same id in it's table. Is it possible to do all of the below in one single query, instead of selecting the data and making loops and ifs?
Basically I want to delete from sessions only if there is 1 hit in session_projects and delete from rec_projects only if there is 1 hit in sessions and all of the hits in session_projects
Is this possible? (please don't mind the unprepared statements in this case)
$pid = 1; // varies
$sql = "SELECT ss_id, rp_id
FROM session_projects
INNER JOIN sessions
ON ss_id = sp_ss_id
INNER JOIN rec_projects
ON rp_id = ss_rp_id
WHERE sp_p_id = $pid";
$session_projects = mysqli_query($db_link, $sql);
while( $row = mysqli_fetch_array($session_projects) )
{
$sql = "SELECT COUNT(*) as session_projects_count FROM session_projects WHERE sp_ss_id = " . $row['ss_id'];
$result = mysqli_query($db_link, $sql);
$session_projects_count = mysqli_fetch_assoc($result);
if( $session_projects_count['session_projects_count'] == 1 )
{
$sql = "SELECT COUNT(*) as sessions_count FROM sessions WHERE ss_rp_id = " . $row['rp_id'];
$result = mysqli_query($db_link, $sql);
$sessions_count = mysqli_fetch_assoc($result);
$sql = "DELETE FROM sessions
WHERE ss_id = " . $row['ss_id'];
$delete_sessions = mysqli_query($db_link, $sql);
if( $sessions_count['sessions_count'] == 1 )
{
$sql = "DELETE FROM rec_projects
WHERE rp_id = " . $row['rp_id'];
$delete_rec_projects = mysqli_query($db_link, $sql);
}
}
}
$sql = "DELETE FROM session_projects
WHERE sp_p_id = $pid";
$delete_session_projects = mysqli_query($db_link, $sql);
You could always aggregate into arrays and delete with IN (), that way you'd have one delete query per table:
// ...
$delSsId = array();
$delRpId = array();
while( $row = mysqli_fetch_array($session_projects) )
{
// ...
if( $session_projects_count['session_projects_count'] == 1 )
{
// ...
$delSsId[] = $row['ss_id'];
if( $sessions_count['sessions_count'] == 1 )
$delRpId[] = $row['rp_id'];
}
}
$sql = "DELETE FROM sessions
WHERE ss_id IN (" . implode(",", $delSsId) . ")";
$delete_sessions = mysqli_query($db_link, $sql);
$sql = "DELETE FROM rec_projects
WHERE rp_id IN (" . implode(",", $delRpId) . ")";
$delete_rec_projects = mysqli_query($db_link, $sql);
The same principle can be applied to your select queries inside the loop; select all rows that could apply into arrays and then use the data from there.
However this could be a bad idea if you have enormously large tables as you might end up loading thousands of rows into arrays, wasting time and memory.
From my personal experience there isn't much performance benefit in optimizing the amount of reading (SELECT) queries anyways, it's usually writing (INSERT, UPDATE, DELETE, ...) queries that have the biggest impact.
I can not seem to come over this easy problem.
I have the following code, where I select the column "status" from a table. There's three different values of "status", 0, 1 and 3.
I would like to count how many 0's there are, 1's and 2's, so that I can display them via <?php echo $accepted; ?> etc.
<?php
$sql = "SELECT status FROM applications";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$array = array_count_values($row);
$pending = $array[0];
$accepted = $array[1];
$denied = $array[2];
?>
MYSQL_NUM changed to MYSQLI_NUM accordingly to comment, thank you.
A simple way is get these count using SQL
$sql = "SELECT `status`, COUNT(*) as cnt FROM applications GROUP BY `status`";
you have an array of so you should
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "status = " . $array['status'] . ' = ' . $array['cnt'] .'<br />';
}
I have a table with a column called 'status'. The defaut value of 'status' is 0. I want to update the value to '1' after using it.
I basically want to check if the status is 0, if it is, do an operation and then change the value to 1.
Here is the code. All works perfectly except that the value of 0 is not changed to 1.
I am a novice so maybe is a very basic mistake :(
<?php
$sql = "SELECT number, status FROM summonerid";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$SummonerID = $row["number"];
$status = $row["status"];
if($status=='0'){
$recentgames=$lol->getRecentGames($SummonerID);
$MatchID1=$recentgames->games[0]->gameId;
$sql = "INSERT INTO matchid (number) SELECT * FROM (SELECT '$MatchID1') AS tmp WHERE NOT EXISTS (SELECT number FROM matchid WHERE number = '$MatchID1') LIMIT 1;";
$sql = "UPDATE summonerid SET status='1' WHERE status='0';"; // THIS IS THE PART THAT DOES NOT WORK WELL
}
}
}
?>
Any help would be highly appreciated
Try this.. you are not executing the sql statements
$sql = "SELECT number, status FROM summonerid";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$SummonerID = $row["number"];
$status = $row["status"];
if($status=='0'){
$recentgames=$lol->getRecentGames($SummonerID);
$MatchID1=$recentgames->games[0]->gameId;
$sql = "INSERT INTO matchid (number) SELECT * FROM (SELECT '$MatchID1') AS tmp WHERE NOT EXISTS (SELECT number FROM matchid WHERE number = '$MatchID1') LIMIT 1;";
$result1 = $conn->query($sql);
$sql = "UPDATE summonerid SET status='1' WHERE status='0';";
$result1 = $conn->query($sql);
}
}
}
?>
I have a rather large query that works fine in Microsoft SQL Server Management Studio. However when I try to run the same query in PHP, I'm getting no results. Here is my code, I know this is the worst way to connect to the database.
Public function GetClockedHours() {
$conn = odbc_connect('easydo', '', '');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql = "WITH ByDays AS ( -- Number the entry register in each day
SELECT
EventTm AS T,
CONVERT(VARCHAR(10),EventTm,102) AS Day,
FLOOR(CONVERT(FLOAT,EventTm)) DayNumber,
ROW_NUMBER() OVER(PARTITION BY FLOOR(CONVERT(FLOAT,EventTm)) ORDER BY EventTm) InDay
FROM CHINA_VISION_DorEvents
Where DorCtrls_Ref = '16' AND CardCode = '000006f1' AND CONVERT(Date,EventTm) > dateadd(day, -7, getdate())
)
,Diffs AS (
SELECT
E.Day,
E.T ET, O.T OT, O.T-E.T Diff,
DATEDIFF(S,E.T,O.T) DiffSeconds -- difference in seconds
FROM
(SELECT BE.T, BE.Day, BE.InDay
FROM ByDays BE
WHERE BE.InDay % 2 = 1) E -- Even rows
INNER JOIN
(SELECT BO.T, BO.Day, BO.InDay
FROM ByDays BO
WHERE BO.InDay % 2 = 0) O -- Odd rows
ON E.InDay + 1 = O.InDay -- Join rows (1,2), (3,4) and so on
AND E.Day = O.Day -- in the same day
)
SELECT Day,
SUM(DiffSeconds) Seconds,
CONVERT(VARCHAR(8),
(DATEADD(S, SUM(DiffSeconds), '1900-01-01T00:00:00')),
108) TotalHHMMSS -- The same, formatted as HH:MM:SS
FROM Diffs GROUP BY Day
ORDER BY Day desc";
$rs = odbc_exec($conn, $sql);
if (!$rs) {
exit("Error in SQL");
}
$array = array();
$i = 1;
while ($row = odbc_fetch_array($rs, $i)) {
foreach ($row AS $key => $value) {
$array[$i][$key] = $row[$key];
}
$i++;
}
var_dump($array);
return $array;
}
The expected result would be an array of results and the results would be:
Date Seconds hours
2015.01.27 18055 05:00:55
2015.01.26 33491 09:18:11
2015.01.23 32649 09:04:09
2015.01.22 31554 08:45:54
2015.01.21 31889 08:51:29
However what were are getting is an array of nothing.
How many results sets do you get back? If it's more than 1 then you need to pick the correct resultset:
bool odbc_next_result ( resource $result_id )
http://php.net/manual/en/function.odbc-next-result.php
I had this same problem. In my case I was executing like this
$sql = "SELECT * FROM table1";
$resultSet = odbc_exec($sqllink, $sql);
while ($data = odbc_fetch_array($resultSet)) {
$sql = "SELECT * FROM table2";
$resultSet2 = odbc_exec($sqllink, $sql);//failed here
while ($data2 = odbc_fetch_array($resultSet2)) {
//something here
}
}
and I changed like this and it worked
$sql = "SELECT * FROM table1";
$resultSet = odbc_exec($sqllink, $sql);
// Create an array and store the results
$queryResult = array();
while ($data = odbc_fetch_array($resultSet)) {
// push the required content into the array
$queryResult[$data['id']]['name'] = $data[name];
}
foreach($queryResult as $row) {
$sql = "SELECT * FROM table2";
$resultSet2 = odbc_exec($sqllink, $sql);
while ($data2 = odbc_fetch_array($resultSet2)) {
// something here
}
}