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 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.
i can't understand why echo don't displays value. Query return values in phpmyadmin sow query is fine. Please help
$query="SELECT `doctor_name` , `doctor_secondname`
FROM `doctors`
INNER JOIN `patients` ON `patients`.doctor_id = `doctors`.doctor_id
WHERE `patients`.patient_id = '{.$patient_id.}'" ;
$result = mysql_query($query) or die(mysql_error());
print_r($row);
if(mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
echo "Your doctor is :";
echo $row['doctor_name'];
echo $row['doctor_secondname'];
}
Try This:
$query="SELECT doctor_name , doctor_secondname
FROM doctors
INNER JOIN patients ON patients.doctor_id = doctors.doctor_id
WHERE patients.patient_id = '".$patient_id."'" ;
Here is my code:
$query1 = "select user, sum(column) as total1 from table1 GROUP BY user";
$result = mysql_query(query1);
$row_query1 = mysql_fech_assoc($result);
do{
$user = $row_query1['user'];
$query2 = "select names, sum(column1) as total2 from table2 WHERE names ='$user' GROUP BY names";
$result2 = mysql_query($query2);
$row_query2 = mysql_fetch_assoc($result2);
$sum = $row_query1['total1'] + $row_query2['total1'];
<tr> <?php echo $sum; ?></tr>
}while($row_query1 = mysql_fech_assoc($result));
I need to get the highest value of $sum from this loop. Can anyone help?
You can do like this.. take a temporary variable($temp) which can have check upon the sum variable($sum).
$query1 = "select user, sum(column) as total1 from table1 GROUP BY user";
$result = mysql_query(query1);
$row_query1 = mysql_fech_assoc($result);
$temp = 0;
do{
$user = $row_query1['user'];
$query2 = "select names, sum(column1) as total2 from table2 WHERE names ='$user' GROUP BY names";
$result2 = mysql_query($query2);
$row_query2 = mysql_fetch_assoc($result2);
$sum = $row_query1['total1'] + $row_query2['total1'];
if($temp < $sum)
$temp = sum;
echo "<tr>$sum</tr>";
}while($row_query1 = mysql_fech_assoc($result));
echo "maximum sum :".$temp;
I would advice doing a JOIN instead of performing the sub queries yourself:
select user, sum(column) + sum(column1) as total
from table1
INNER JOIN table2 ON names = user
GROUP BY user
The rest should be straightforward in code.
Database:
table #1: xx_users (id, name, user_id, location, network)
table #2: xx_questions (id, user_id, time)
Code:
$friends = $facebook->api('/me/friends');
$arr = $friends['data'];
$friend_ids_arr = array();
foreach($arr as $friend) {
$friend_ids_arr[] = $friend['id'];
}
$sql = "SELECT q.*, u.location, u.network
FROM xx_questions q
JOIN xx_users u
ON q.user_id = u.user_id
AND (q.user_id = $user) OR
q.user_id IN (".implode(',', $friend_ids_arr).") OR
u.location = (SELECT location FROM xx_users WHERE user_id = $user) OR
u.network = (SELECT network FROM xx_users WHERE user_id = $user)
ORDER BY q.time DESC";
$data = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($data)) {
if ($row['anon'] == 1) {
$asker = "<span style='color: #333;'>Anonymous</span>";
}
else {
$asker_name = json_decode(file_get_contents("http://graph.facebook.com/".$row['user_id']))->name;
$asker = "<a href='user.php?id=".$row['user_id']."'><b>".$asker_name."</b></a>";
}
echo "<div class='question'>";
echo "<a href='q.php?id=".$row[id]."' class='left'>".$row['question']."</a><span style='color: #666'> ";
$sql2 = "SELECT * FROM xx_answers WHERE question_id = '".$row[id]."'";
$result = mysql_query($sql2);
$xxx = mysql_num_rows($result);
echo "($xxx)";
echo "</span>";
echo "<div class='right'><span style='color: #999'>";
$to_time = strtotime("now");
$from_time = strtotime(".$row[time].");
$since = $to_time-$from_time;
time_since($since);
echo " by <a href='user.php?id=".$row['user_id']."'><b>".$asker."</b></a></span></div>";
echo "<div style='clear:both;'></div>";
echo "</div>";
}
I am using this code to echo three sorts of questions from the database:
Where the user is Facebook friends with the poster
Where the user is in the same location as the poster
Where the user shares a network with the poster
This all works fine except all of the values are echoed twice. The weird thing is that when I only echo one of the above 3, the values are only echoe once as intended. Any idea why this is happening?