Combining arrays from different MySQL entries and removing duplicates - php

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

Related

Counting the top checkbox responses when responses are stored as comma separated string in mysql row (Google Form -> mysql)

A form's checkboxes are stored as comma separated values in a single row as a string in mysql. I cannot control this.
When trying to get the top responses, both finding what the responses are, and how many times they appear, I run this:
$query = "SELECT `answer`, COUNT(*) AS CNT FROM `responses` WHERE `answer` <> '' GROUP BY `answer` ORDER BY CNT DESC ";
The individual comma separated values are not counted, rather the combination of them.
Example, 4 people submit checkboxes A and B. 2 only select A, 1 selects A and B, 1 selects B
The result of query above looks like:
A (2)
A,B (1)
B (1)
What I want to achieve is it separating the comma seperated values and yielding:
A (3)
B (2)
I have seen some php explode examples and tried as follows:
if ($result->num_rows > 0) {
while($rows = mysqli_fetch_assoc($result)) {
$ans=explode(',', $rows['answer']);
foreach($ans as $separated) {
echo "<div>".$separated."</div>";
}
}
The result looks like:
a
a
a
b
b
Now how do I store them to count, and then order from most selected to least?
Is my best route to use explode? Or is there another way that is simpler and more logical?
This link explains the issue, and they have a google side fix, but mysql doesn't have the commands: https://support.google.com/docs/thread/54705332?hl=en
Thanks!
###########################################
As answered below, the new code is:
$query = "SELECT `ans_4` FROM `responses` WHERE `ans_4` <> ''";
$result = $conn->query($query);
if ($result->num_rows > 0) {
$ans = [];
while($rows = mysqli_fetch_assoc($result)) {
$ans = array_merge($ans, explode(', ', $rows['answer']));
}
$count = array_count_values($ans);
arsort($count);
foreach ($count as $key => $value) {
echo "<div><span>$key</span><span>$value</span></div>";
}
For PDO:
$stmt = $pdo->query("SELECT ans_4 FROM responses WHERE ans_4 <> ''");
$ans = [];
while ($rows = $stmt->fetch(PDO::FETCH_ASSOC))
{
$ans = array_merge( $ans, explode( ', ', $rows[ 'ans_4' ] ) );
}
$count = array_count_values( $ans );
arsort( $count );
echo( "Largest Concerns" );
foreach ( $count as $key => $value ) {
echo "<div><span>$key</span><span>$value</span></div>";
}
Obviously this is not the best way to store them, and I'm not sure if you can do it in the query. But you probably want to just select that column:
SELECT `answer` FROM `responses` WHERE `answer` <> ''
Then explode and add to a flat array and count the values:
$ans = [];
while($rows = mysqli_fetch_assoc($result)) {
$ans = array_merge($ans, explode(',', $rows['answer']));
}
$count = array_count_values($ans);
The $count array should then yield something like:
Array
(
[A] => 3
[B] => 2
)
Then if needed to sort descending:
arsort($count);

Get last ID number from table

I tried this:
<?php
$query = "SELECT MAX(ID) FROM Table";
$result=sqlsrv_query($conn, $query);
$values = sqlsrv_fetch_array($result);
var_dump($values);
echo $values;
?>
But I got this on my webpage:
C:\wamp64\www\site\site.php:18:
array (size=2)
0 => int 1
'' => int 1
Am I missing something?
$values is an array, so you need to access the direct value if you want to echo it. The max ID is 1, as shown by your var_dump() - but you get two results from the array $values, one associative and one numeric indexed. If you alias your data from the query, you can then fetch the associative value by name of that alias.
<?php
$query = "SELECT MAX(ID) as maxID FROM Table";
$result=sqlsrv_query($conn, $query);
$values = sqlsrv_fetch_array($result);
echo $values['maxID'];
Or if you want to access it numerically,
<?php
$query = "SELECT MAX(ID) FROM Table";
$result=sqlsrv_query($conn, $query);
$values = sqlsrv_fetch_array($result);
echo $values[0];

Values of keys in different arrays

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'));

splitting an array with single key and string value into an array with multiple keys and values

I have a table which stores the courses registered by students during a semester and session. I populated it with course-codes for a particular student. Here is the function that fetches the course-code below:
function get_course_code(){
global $connection;
$query = "SELECT DISTINCT course_code ";
$query .= "FROM tbl_registered_courses_400 ";
$query .= "WHERE matric_no = '03/55ec101' LIMIT 10";
$course_code_set = mysql_query($query, $connection);
confirm_query($course_code_set);
return $course_code_set;
}
When I called the function in my main page. It returned the following result
$courseCode = get_course_code();
$courseFilter = '';
while ($courseList = mysql_fetch_array($courseCode)){
$courseList['course_code'];
$courseFilter .= "\""."{$courseList['course_code']}"."\",";
$courseFilter;
}
$course = array($courseFilter);
print_r($course);
Array ( [0] => "PHY 432","CSC 491","CHM 401","CHM 402","MAT 451","MAT 452","CSC 423","BLY 401", )
I want to split the $course array into an array that will have the values of the string in the above to read
array(
[0] => PHY 432
[1] => CSC 491
[2] => CHM 401
[3] => CHM 402
.
.
.
e.t.c
)
The string data in the $course array is from the course_code column in the database.
My intention is to use the results of the new array to form a row in the database that will hold the results of each matric_no for different courses done for the semester/session. I would appreciate any help I can get to get this done.
create the array and then assign the values to that array.
$courseCode = get_course_code();
$course = array();
while ($courseList = mysql_fetch_array($courseCode)){
$course[] = $courseList['course_code'];
}
print_r($course);

mysql SELECT a whole column or cycle through all IDs

I need to select a whole column.
So my question is how do i get a whole column ?
$query = "SELECT * ";
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";
I tried id=* but no luck ...
My goal is to cycle through all IDs but some may be missing so i figured i put them in a numeric or associative array and use foreach. If there is a better way , please do share.
EDIT:
function get_all_ids()
{
global $connection;
$query = "SELECT * ";
$query .= "FROM employees ";
$query_result = mysql_query ( $query , $connection );
confirm_query($query_result);
$query_result_array = mysql_fetch_assoc($query_result);
return $query_result_array;
}
i use this to print the array
$all_id = get_all_ids();
// preparing the table;
echo "<pre>";
print_r($table);
print_r($all_id);
echo "</pre>";
and this is the array
Array
(
[id] => 1
[department_id] => 1
[name] => jordan
[EGN] => 9108121544
[email] => testEmail
[address] => testAddress
[country] => testCounty
)
If there's more than one row in your result set, you need to keep fetching until all results are retrieved:
$q = mysql_query('SELECT * FROM `table`');
while (($row = mysql_fetch_assoc($q)) != FALSE)
{
// Do something with *one* result
}
mysql_free_result($q);
If you'd like to retrieve all ids in a single fetch, you could do:
$q = mysql_query('SELECT GROUP_CONCAT(`id`) AS `id_list` FROM `table`');
$row = mysql_fetch_assoc($q);
mysql_free_result($q);
$list_of_ids = explode(',', $row['id_list']);
WARNING: GROUP_CONCAT() usually has a result limit of 1024 bytes; meaning your results will be truncated for large tables. You could either resort to the first solution, or increase group_concat_max_len for the current connection.
If you want ALL the records then you dont need a WHERE condition at all.
Perhaps you mean the simple:
SELECT id
FROM employees
ORDER BY id ASC
If this gives you only one row, then either you have only one row or you are adding a LIMIT 1 or your PHP code does not loop through all the results but just shows the first one of them. Please add the PHP code.
If you want to select a single column. Then do not use "*", give the name of the columns name separated by comma and quoted with "`" (tick) for safety.
$query = "SELECT `id` "; //if you only want to get ids from the table
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";

Categories