i have made this code to get the top 5 songs views:
$mysqli_query ="SELECT page, count( * ) AS 'Cnt'
FROM pageview
GROUP BY page
ORDER BY `Cnt` DESC
LIMIT 5 ";
$result = mysqli_query($conn, $mysqli_query) or die (mysqli_error($conn));
$num_rows = mysqli_num_rows($result);
echo "<br>Top 5 Song views:<br>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo " " .$row["page"]."<br />";
}
} else {
echo "0 results";
}
//fim
mysqli_close($conn);
?>
And it is working, but the $row["id"] is missing, in my mind i have to make another query, my question is can i join this in the existing query?
maybe you should do this
$mysqli_query ="SELECT id,page, count( * ) AS 'Cnt'
FROM pageview
GROUP BY page
ORDER BY `Cnt` DESC
LIMIT 5 ";
Related
I'm trying to code a php script, which can find if the last 10 rows from mySQL database are the same. And if the values are same, then the script could sent an email.
I can fetch the last 10 rows.
$sql = ("SELECT ID, DayTime,Temperature FROM AllinOne ORDER BY ID DESC LIMIT 10");
$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"]. " - DayTime: " . $row["DayTime"]. " - Temperature " . $row["Temperature"]. "<br>";
}
} else {
echo "0 results";
}
Last 10 results:
Now, I'm trying to check if last 10 rows in "Temperature" column are the same (as we can see).
I use:
$sql2 = "SELECT Temperature, COUNT(*) as duplicates FROM AllinOne GROUP BY Temperature ORDER BY ID DESC LIMIT 10";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0)
{
// output data of each row
while($row2 = $result2->fetch_assoc())
{
echo $row2["duplicates"]. "<br>";
}
}
but I can't take back the same results (i can't understand the final result).
$row2 results
Could you help me???
Execute the following query and grab the result:
SELECT
COUNT(*) AS count_rows,
MIN(Temperature) AS min_temperature,
MAX(Temperature) AS max_temperature
FROM (
SELECT *
FROM t
ORDER BY DayTime DESC
LIMIT 10
) AS x
Then send an email if count_rows = 10 and min_temperature = max_temperature.
You just need to fix your second query like:
$sql2 = "SELECT Temperature, COUNT(*) as duplicates
FROM (
SELECT ID, DayTime, Temperature FROM AllinOne ORDER BY ID DESC LIMIT 10
) LastData
GROUP BY Temperature";
Here you can test PHP code with queries
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 have the following query and it gives me the percentage. It works great and i echo it in a table. In this table i also want to echo the AVG % as a total.i.e i have 12 months of year and want the avg. % for the year at the bottom of the table. I have worked out how to do this for valuations and instructions that are stored in my database. But.. how do i do this for a 'virtual' column like %..as this has been created from a query and not a physical column in the database.
iam starting to think i need to combine the total valuations by total instructions to get my %. Any ideas how i can do this?
$query= "SELECT *,
concat(round(( instructions/valuations * 100 ),0),'%') AS percentage
FROM office_figures2016";
$result = mysqli_query($conn, $query);
while($office_figures2016=mysqli_fetch_assoc($result)){
it echos :
echo"".$office_figures2016['percentage']."";
and here is the php to get the totals for each column...the third part of code is wrong but this is what i have so far:
<?php
$sql = "SELECT ROUND(AVG(valuations),0) AS value_sum FROM office_figures2016";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<td> " . $row["value_sum"]."</td>";
$sql = "SELECT ROUND(AVG(instructions),0) AS value_sum FROM office_figures2016";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<td> " . $row["value_sum"]."</td>";
// need to divide total valuations by total instructions x 100 = %
// somehow need to combine the value sums together.. if?
$sql = "SELECT ROUND(AVG(''),0) AS value_sum FROM office_figures2016";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<td> " . $row["value_sum"]."</td>";
I redid the formula to divide all instructions and valuations in the table x100 = %.
$sql = "SELECT ROUND(AVG(instructions / valuations *100 ),0) AS value_sum FROM office_figures2016";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<td> " . $row["value_sum"]."</td>";
I have a db with columns like the following:
id options
1 Website,Website,Newspaper,Newspaper,TV,TV,Radio,Radio
2 Website,Website,Newspaper,Newspaper
3 Website,Website,TV,TV
The goal is to remove the duplicate entries and normalize the options column to:
id options
1 Website,Newspaper,TV,Radio
2 Website,Newspaper
3 Website,TV
I have developed the following PHP code:
$sql = "SELECT id, options FROM table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$values_array = explode( ',' , $row['options'] );
if(count($values_array) != count(array_unique($values_array)))
{
$likes = array_unique($values_array);
$new = implode(',', $likes);
$sql = "UPDATE table SET options=".$new." WHERE id = '$id'";
}
}
} else {
echo "0 results";
}
$conn->close();
This doesn't get the job done. Everything seems to work but the attempt to update the options columns with the new array data.
This doesn't seem too difficult, just looking for a little guidance on how to make it work.
Thanks in advance!
You can do it directly in mysql
UPDATE T
JOIN
(SELECT id,GROUP_CONCAT(DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(t.options, ',', sub0.aNum), ',', -1)) AS ids
FROM t
INNER JOIN
(
SELECT 1 + units.i + tens.i * 10 AS aNum, units.i + tens.i * 10 AS aSubscript
FROM (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units
CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens
) sub0
ON (1 + LENGTH(t.options) - LENGTH(REPLACE(t.options, ',', ''))) >= sub0.aNum
GROUP BY id)x
ON x.id=t.id
SET t.options=x.ids
FIDDLE
Inspired by this answer
Try This:
$sql = "SELECT id, options FROM table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$values_array = explode(',', $row['options']);
if (count($values_array) != count(array_unique($values_array))) {
$likes = array_unique($values_array);
$new = implode(',', $likes);
$sql = "UPDATE table SET options=" . $new . " WHERE id = '$id'";
/* seems you missed this */
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
/* you declared sql query but not executed it */
}
}
} else {
echo "0 results";
}
$conn->close();
hope it was helpful :)
As stated in other answers, your quotes are wrong and you didn't execute the UPDATE query, there's another thing you need to know.
table is a reserved keyword in MySQL, so you can't use it like that in your query. Use backticks to escape it.
So your code should be like this:
$sql = "SELECT id, options FROM `table`";
$result = $conn->query($sql);
if ($result->num_rows > 0){
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$values_array = explode( ',' , $row['options'] );
if(count($values_array) != count(array_unique($values_array))){
$likes = array_unique($values_array);
$new = implode(',', $likes);
$sql = "UPDATE `table` SET options='".$new."' WHERE id = '$id'";
$conn->query($sql);
if($conn->affected_rows){
echo "success<br />";
}else{
echo "error<br />";
}
}
}
}else{
echo "0 results";
}
$conn->close();
Here's the reference:
Keywords and Reserved Words
I added the following code to my PHP as showcased by Ajjay Aroraa --
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
The final code for my entire application:
$sql = "SELECT id, options FROM tdata";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$values_array = explode( ',' , $row['options'] );
if(count($values_array) != count(array_unique($values_array)))
{
// find duplicate values in the array
$likes = array_unique($values_array);
$new = implode(',', $likes);
$sql = "UPDATE tdata SET options='".$new."' WHERE id = '$id'";
// execute update query
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
}
} else {
echo "0 results";
}
$conn->close();
Thanks to all who replied -- this is a quick fix as I work to normalize the tables.
My code looks like this:
$sql = "SELECT `sw1`, `sw2`, `sw3`, `sw4`, `fb1`, `fb2`, `fb3`, `fb4`, `bew1`, `bew2`, `bew3`, `bew4` FROM `reg` WHERE `id` = ".$id." ORDER BY `id` ASC LIMIT 0, 30 ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
foreach($row as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
}
}
There is some data in sw2 but it isn't shown.
When I tryed to UPDATE data the data in the db wasn't changed.
$id is right.
other data from the table could be read.
This code works fine:
$sql = "SELECT * FROM `reg` WHERE `id` = ".$id." ORDER BY `id` ASC LIMIT 0, 30 ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
print_r($row);
}
Try your query with echo.
same trouble follows try changing Where 'id' = "$id"
to Where 'id' like "$id"
You dont need quotes:
$sql = "SELECT sw1, sw2, sw3, sw4, fb1, fb2, fb3, fb4,
bew1, bew2, bew3, bew4
FROM reg WHERE id = $id";