So I have a query that returns the following results in PHP, and I'm trying to add the total of the hours_played, I have tried array_sum() but that does not seem to work, I would like to be able to add the values of hours_played to be 11 that way I can then pass that it another function :
Array
(
[id] => 1
[team_id] => 1
[hours_played] => 1
)
Array
(
[id] => 2
[team_id] => 1
[hours_played] => 4
)
Array
(
[id] => 3
[team_id] => 1
[hours_played] => 6
)
I'm a little bit lost and do I need to store the able Arrays in another array to be able to do this? The results above are from a sql query and is what is printed on the page when I print_r the $row variable.
$sql = "SELECT * FROM table1 WHERE team_id = 1";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)){
print_r($row);
}
You can either sum all the columns hours_played after having fetched the results and assigned them into an array, as shown below
$sql = "SELECT * FROM table1 WHERE team_id = 1";
$res = mysql_query($sql);
$result = array();
while($row = mysql_fetch_assoc($res)){
$result[] = $row;
}
$sum = array_sum(array_column($result, "hours_played"));
echo $sum;
..or you can sum it up as you loop the results.
$sql = "SELECT * FROM table1 WHERE team_id = 1";
$res = mysql_query($sql);
$sum = 0;
while($row = mysql_fetch_assoc($res)){
$sum += $row['hours_played'];
}
echo $sum;
Or, if you just need the total hours played, you can do that directly in one query, using COUNT() in MySQL.
$sql = "SELECT SUM(hours_played) as sum_hours_played FROM table1 WHERE team_id = 1";
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
echo $row['sum_hours_played'];
PHP array_column()
PHP array_sum()
MySQL COUNT()
WARNING
Do not use mysql_* functions in new code. They are no longer maintained and are officially deprecated.
See the red box?
Learn about prepared statements instead, and use PDO or MySQLi
- this article can help you decide which.
You're really close . You just need to add the 3rd index of each array together:
$sql = "SELECT * FROM table1 WHERE team_id = 1";
$res = mysql_query($sql);
$total = 0;
while($row = mysql_fetch_assoc($res)){
$total += $row['hours_played'];
}
CONVERSELY You can use the numbered index as well.
$total = 0;
while($row = mysql_fetch_assoc($res)){
$total += $row[2]; // indexes start at 0
}
echo $total; // Will print 11 if your arrays you posted are correct.
IN ADDITION --- WARNING!! You need to be using mysqli instead of the far less secure and now deprecated mysql
Most Important
Avoid using mysql_* functions. They are no longer maintained and are also officially deprecated.
Read about using prepared statements instead, and change your existing code to use PDO or MySQLi
You can get a total of hours_played in the while loop. Try this:
$sql = "SELECT * FROM table1 WHERE team_id = 1";
$res = mysql_query($sql);
$total_hours_played = 0; // initialize a variable to get sum of hours
while($row = mysql_fetch_assoc($res)){
$total_hours_played += $row['hours_played'];
}
echo $total_hours_played;
$sum = array_sum(array_column($array, 'hours_played'));
Related
I am creating a time attendance PHP script. I started from storing data in the database MySQL and use different tables for the Punch-in/Punch-out, Breaks, Lunch/Dinner breaks.
Each one of the casualties mentioned before have a table which is structured with an:
ID, start, end, flag
I have already tried to do this with the following code of foreach but unsuccessfully!
foreach ($total as $key => $row) {
$start[$key] = $row['start'];
}
$final = array_multisort($start, SORT_DESC, $total);
echo $final;
Here is the code that I have made with 2 SELECT MySQL queries
$result = mysqli_query($db, "SELECT * FROM time WHERE username =
'$user_check' ORDER BY start DESC");
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
} $db->next_result();
$result = mysqli_query($db, "SELECT * FROM break WHERE username =
'$user_check' ORDER BY start DESC");
$data2 = array();
while ($row = mysqli_fetch_assoc($result)) {
$data2[] = $row;
}
$total = array_merge ($data, $data2);
I would like to have 1 array of this 2 queries sorted DESC by start as I will use this array to populate a table in DESC order.
Use UNION ALL in your query, instead of merge arrays. Let the database do the work for you:
SELECT * FROM
(SELECT * FROM time WHERE username = '$user_check'
UNION ALL
SELECT * FROM break WHERE username = '$user_check'
) ORDER BY start DESC
PS: Your code is vulnerable to SQL Injection. You should use prepared statement instead.
I have a MySQL database with varying rows and a specific column with arrays which I wish to combine and then remove the duplicates. For example, the following entries, row1 ([0] => 1) row2 ([0] => 2 [1] => 3) and row3 ([0] => 1 [1] => 2 [2] => 3). I need to combine them and remove duplicates like this:
rows ([0] => 1 [1] => 2 [2] => 3)
I have called the query from the database as follows and since the entries are stored by comma separation, (1,2,3), I used the explode function to get them in the format above.
$query2 = "SELECT * FROM samples_database WHERE order_id=$order_id AND micro_analysis<>'';";
$result2 = mysqli_query($conn, $query2);
$input = mysqli_fetch_array($result2);
$micro_analysis = $input['micro_analysis'];
$micro_analyses = explode(',', $micro_analysis);
print_r($result2);
From here I cannot seem to get the array from each separate row, it only gives a array result from the first row and thus affects my downstream results. How can I achieve this goal?
Store it as comma separated string and then explode it and make it unique. You can then use array_filter to remove any null or empty values
Also, you have missed looping the result set to fetch all values returned from the query.
Here' is the updated snippet,
$query2 = "SELECT * FROM samples_database WHERE order_id=$order_id AND micro_analysis<>'';";
$result2 = mysqli_query($conn, $query2);
$micro_analysis = '';
while($input = mysqli_fetch_array($result2))
{
$micro_analysis .= $input['micro_analysis'] . ',';
}
$micro_analysis_arr = array_filter(array_unique(explode(',', $micro_analysis)));
$query2 = "SELECT * FROM samples_database WHERE order_id=$order_id AND micro_analysis<>'';";
$result2 = mysqli_query($conn, $query2);
$micro_analysis = array();
while($input = mysqli_fetch_array($result2))
{
$micro_analysis[] = $input['micro_analysis'];
}
$micro_analysis_arr = array_unique($micro_analysis);
Hope this will help you
How to make the array of id that we call from a table?
What I want is like this :
$array = array(1, 2, 3, 4, 5); // **1 - 5 select from a table**.
Thank you
Code :
$query = mysqli_query($conn, "SELECT * FROM tableA");
while($row = mysqli_fetch_assoc($query )){
$a = implode(',',(array)$row['id_add_user']);
echo $a;
}
What I get from echo $a is 12345 not 1,2,3,4,5
Add all the elements to an array, then implode() it into one string with your desired deliminator (here, its ", ") once all results are fetched.
$result = [];
$query = mysqli_query($conn, "SELECT * FROM tableA");
while($row = mysqli_fetch_assoc($query)){
$result[] = $row['id_add_user']);
}
echo implode(", ", $result);
Collect necessary values into an array.
$a = [];
while(...){
$a[] = $row['id_add_user'];
}
echo implode(',', $a);
You are trying to implode() the values for each row, you need to build an array of all the values and then output the result imploded. Also if you just want one column - just fetch that column in your SQL
You can further simplify it to...
$query = mysqli_query($conn, "SELECT id_add_user FROM tableA");
$rows = mysqli_fetch_all($query );
echo implode(',',array_column($rows, 'id_add_user' ));
mysqli_fetch_all allows you to fetch all the data in one go. Then use array_column() to extract the data.
$array = array(1,2,3,4,5);
Use below SQL query for selecting the array id data
SELECT column_name(s)
FROM table_name
WHERE column_name IN $array;
UPDATE: a solution has been found stated below: however new issue poses i didnt want to keep creating question so updated this one when i use ajax to pass through to html i get the following error response.forEach is not a function
where the code is as below is this because there are now 2 arrays?
$.get('php/test.php', function(response) {
console.log(response);
var row;
response.forEach(function(item, index) {
console.log(item);
$(`td.${item.beacon}`).css('background-color', item.location).toggleClass('coloured');
});
});
Im Pretty naff when it comes to this type of thing but i need to try get these 2 queries added to 1 ajax I have been told i should add both queries to an outer array but im not sure how to do this and the example i got was $array = $other_array
but im not sure how to write it any help would be greatly appreaciated
$sql = "SELECT beacon,TIME_FORMAT(TIMEDIFF(max(`time`),min(`time`)), '%i.%s')
AS `delivery_avg`
FROM `test`.`test`
where date = CURDATE()
and time > now() - INTERVAL 30 MINUTE
group by beacon ";
$result = $conn->query($sql);
$sql2 = 'SELECT
*
FROM
(SELECT
beacon,location,date,
COUNT(location) AS counter
FROM `test`.`test`
WHERE `date` = CURDATE() and `time` > NOW() - interval 40 second
GROUP BY beacon) AS SubQueryTable
ORDER BY SubQueryTable.counter DESC;';
$result = $conn->query($sql2);
$result = mysqli_query($conn , $sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
$result2 = mysqli_query($conn , $sql2);
$rows2 = array();
while($r = mysqli_fetch_assoc($result2)) {
$rows2[] = $r;
}
echo json_encode($rows2);
You already got most of it right. To get the data in one go, you can combine the arrays (see the line staring with $result) and then send it JSON formatted.
$sql1 = "SELECT ...";
// Query the database
$result1 = $conn->query($sql);
// Fetch the result
$rows1 = $result1->fetch_all(MYSQLI_ASSOC);
// Same for second query
$sql2 = 'SELECT ...';
$result2 = $conn->query($sql2);
$rows2 = $result2->fetch_all(MYSQLI_ASSOC);
$result = array(
'query1' => $rows1,
'query2' => $rows2
);
header("Content-Type: application/json");
echo json_encode($result);
Some more hints:
You only need to run the query once (you have ->query() and mysqli_query() in your code).
You don't need the loop to get all result rows. The function mysqli_fetch_all() does that for you.
When you have your 2 arrays with db results, you can do something like this :
$return = array (
$result,
$result2
);
echo json_encode($return);
$sendResponse = array (
'sql1' => $sqlResult1,
'sql2' => $sqlResult2
);
echo json_encode($sendResponse);
This would be a more suitable and convenient (from JavaScript size) way
$response = [];
$response['result_first_query'] = $rows;
$response['result_second_query'] = $rows2;
echo json_encode($response);
Suppose I have a while loop like:
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
}
then if first query return 5 results i.e 1-5 and second query returns 3 results than if i want to echo out second query it gives me like this..........
111112222233333
than how can i fix to 123 so that the second while loop should execute according to number of times allowed by me........!! how can i do that.........!!
I'm not sure I 100% understand your question - it's a little unclear.
It's possible you could solve this in the query with a GROUP BY clause
$sql_2 = mysql_query("SELECT id FROM secondtable WHERE id != $id GROUP BY id");
But that would only work if you need just secondtable.id and not any of the other columns.
When you say "number of time allowed by me" do you mean some sort of arbitrary value? If so, then you need to use a different loop mechanism, such as Greg B's solution.
Do you want to explicitly limit the number of iterations of the inner loop?
Have you considered using a for loop?
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
for($i=0; $i<3; $i++){
$ro = mysql_fetch_array($sql_2);
$id2 = $ro["id2"];
echo $id2;
}
}
Your first while loop is iterating over all 5 results, one at a time.
Your second while loop is iterating over each of the 5 results, producing it's own set of results (i.e. 3 results for each of the 5 iterations, totaling 15 results).
I believe what you are trying to do is exclude all IDs found in your first loop from your second query. You could do that as follows:
$sql = mysql_query("SELECT * FROM tablename");
$exclude = array();
while($row = mysql_fetch_array($sql)) {
array_push($exclude, $row['id']);
}
// simplify query if no results found
$where = '';
if (!empty($exclude)) {
$where = sprintf(' WHERE id NOT IN (%s)', implode(',', $exclude));
}
$sql = sprintf('SELECT * FROM secondtable%s', $where);
while($row = mysql_fetch_array($sql_2)) {
$id2 = $row["id2"];
echo $id2;
}
$sql = mysql_query("SELECT * FROM tablename");
$tmp = array();
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
if(!in_array($id, $tmp)) {
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
$tmp[] = $id;
}
}
Saving all queried $id's in an array to check on the next iteration if it has already been queried. I also think that GROUPing the first query result would be a better way.
I agree with Leonardo Herrera that it's really not clear what you're trying to ask here. It would help if you could rewrite your question. It sounds a bit like you're trying to query one table and not include id's found in another table. You might try something like:
SELECT * FROM secondtable t2
WHERE NOT EXISTS (SELECT 1 FROM tablename t1 WHERE t1.id = t2.id);