Merging arrays to the one array from while loop - php

I need an information to put from DB to arrays and then make one array.
So I wrote a following code:
$sql0 = "SELECT * FROM ".$working_table." ORDER by id ASC";
$result = mysqli_query($conn, $sql0);
$num_rows = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result)){
${"emails_arr$row[id]"} = explode(",",$row['station_email']);
echo print_r(${"emails_arr$row[id]"})."<br>";
}
$sql0 = "SELECT * FROM ".$working_table." ORDER by id ASC";
$result = mysqli_query($conn, $sql0);
$num_rows = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result)){
$result_array = array_merge(${"emails_arr$row[id]"});
}
echo print_r($result_array);
the tricky part is that i don't know how to merge an arrays to one array from the while loop: $result_array = array_merge(${"emails_arr$row[id]"});
it only shows the last array, other arrays are being rewrote.
Thank you guys!

Change your while loop code with this one
while($row = mysqli_fetch_array($result)){
$result_array[] = array_merge(${"emails_arr$row[id]"});
}
Notice the Square Brackets.

Related

How to merge an array inside another array in php?

Im trying to merge or put an Array (called '$rows_ban') inside a sub item of another array (called '$rows') in a final array named '$rows_final'.
Im using array_merge but returns null inside 'data':
{"date":"2018-05-03","hour":"09:12:32","data":[null]}
It should return the results in of the second query inside the 'data':
{"date":"2018-05-03","hour":"09:12:32","data":[{...},{...},{...}]}
PHP Script:
$rows = array();
$rows_ban = array();
$rows_final= array();
$result1 = mysqli_query($link,"SELECT `id`,`sync_date`,`sync_time` FROM sync_log");
while($r = mysqli_fetch_array($result1)) {
$rows['date']= $r[2];
$rows['hour']= $r[3];
$rows['data'][]= null;
}
$result2 = mysqli_query($link,"SELECT cod, name, total from totals " );
while($r = mysqli_fetch_array($result2)) {
$rows_ban['cod'] = $r[0];
$rows_ban['name'] = $r[1];
$rows_ban['total'] = $r[2];
$result3 = mysqli_query($link,"SELECT *, 1 as Filter from
table3 where cod=".$r[0]." order by dates desc");
while($r = mysqli_fetch_assoc($result3)) {
$rows_ban['sub_data'][] = $r;
}
$rows_final = array_merge($rows['data'],$rows_ban);
// here im trying to merge the $rows_ban array inside the
$rows['data']
}
echo json_encode($rows_final);
Not sure if that's what you wanted to accomplish since your description is very poor and hard to understand.
$output = [];
$tmpRows = [];
$result = mysqli_query($link, 'SELECT `id`,`sync_date`,`sync_time` FROM sync_log');
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$output['date'] = $tmp[0]['sync_date'];
$output['time'] = $tmp[0]['sync_time'];
}
$result = mysqli_query($link, 'SELECT cod, name, total from totals ');
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$tmpRows['cod'] = $tmp[0]['cod'];
$tmpRows['name'] = $tmp[0]['name'];
$tmpRows['total'] = $tmp[0]['total'];
$result = mysqli_query($link,"SELECT *, 1 as Filter from
table3 where cod={$tmp[0]['cod']} order by dates desc");
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$tmpRows['sub_data'] = $tmp[0];
}
$output['data'] = $tmpRows;
}
print_r(json_encode($output));
Also array_merge doesn't work like you think it does. It returns merged array like it's name states. Regarding to your code, final result would be exactly $rows_ban encoded to json.
http://php.net/manual/en/function.array-merge.php

Getting an array to string conversion error

Can someone help me what's the problem with this code? Im trying to store the fetched data to an array and i want to based on the values of that array. Im getting an error of Array to string conversion. The datatype value of an array is string
Here's the code.
$sql3 ="SELECT DISTINCT subj_descr FROM subj_enrolled WHERE enroll_ref = '$ref'";
$results = mysqli_query($con, $sql3);
$data = array();
while($row = mysqli_fetch_array($results)){
$data[] = array($row['subj_descr']);
}
$sql ="SELECT * FROM notification WHERE subj_descr IN ({implode(',', $data})";
$result = mysqli_query($con, $sql);
$count = mysqli_num_rows($result);
Remove array inside your while loop:
$sql3 ="SELECT DISTINCT subj_descr FROM subj_enrolled WHERE enroll_ref = '$ref'";
$results = mysqli_query($con, $sql3);
$data = array();
while($row = mysqli_fetch_array($results)){
$data[] = $row['subj_descr'];
}
$sql ="SELECT * FROM notification WHERE subj_descr IN ({implode(',', $data})";
$result = mysqli_query($con, $sql);
$count = mysqli_num_rows($result);
create a new variable and implode in it.
Try this
$implodeAray = implode(",", $data);
$sql ="SELECT * FROM notification WHERE subj_descr IN ($implodeAray)";
You are creating a multidimensional array and so change this statement
$data[] = array($row['subj_descr']);
to
$data[] = $row['subj_descr'];
As SQL IN statement always used a single dimensional array so also make change in query where clause.
I have changed all, please try below code:
<?php
$sql3 ="SELECT DISTINCT subj_descr FROM subj_enrolled WHERE enroll_ref = '$ref'";
$results = mysqli_query($con, $sql3);
$data = array();
while($row = mysqli_fetch_array($results)){
$data[] = $row['subj_descr'];
}
$dataStr = implode(',', $data);
$sql ="SELECT * FROM notification WHERE subj_descr IN (".$dataStr.")";
$result = mysqli_query($con, $sql);
$count = mysqli_num_rows($result);
?>
You stored the element of your array inside another array while looping.
Do this:
$sql3 ='SELECT DISTINCT subj_descr
FROM subj_enrolled
WHERE enroll_ref = "$ref"';
$results = mysqli_query($con, $sql3);
$data = array();
while($row = mysqli_fetch_array($results)){
//Your error was here
//Each elements is escaped for security reasons
$data[] = mysqli_escape_string($con,$row['subj_descr']);
}
//This implodes and puts a single quote around each element
$dataIn= '\'' . implode( '\', \'', $data ) . '\'';
$sql ="SELECT * FROM notification
WHERE subj_descr IN ($dataIn)";
$result = mysqli_query($con, $sql);
$count = mysqli_num_rows($result);

Getting exact value from fetched array from MySql

Not a duplicate of Select specific value from a fetched array
I have a MySql database as:
Here's my query:
$sql = "SELECT * FROM data ORDER BY Score DESC";
I want it to be a leaderboard which people can update their scores so I can't use
$sql = "SELECT * FROM data ORDER BY Score DESC WHERE ID = 1";
I want to get Username of the second row in my query.So I wrote:
<?php
include "l_connection.php";
$sql = "SELECT * FROM data ORDER BY Score";
$result = mysqli_query($conn, $sql);
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
}
echo "Result = '".$row[1]['Username']."''";
}
?>
But it returns Result = '' like there's nothing in the array.
But if I write
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "Name = '".$row['Username']."''";
}
}
It will return : Parham, Mojtaba, Gomnam, Masoud,
So what am I doing wrong in the first snippet?
You can not access $row outside of while loop.
So store result in one new array, and then you can access that new array outside the while loop:
$newResult = array();
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$newResult[] = $row;
}
}
echo "Result = '".$newResult[1]['Username']."''"; // thus you can access second name from array
Because you write where condition after ORDER by at
$sql = "SELECT * FROM data ORDER BY Score DESC WHERE ID = 1";
The sequence of query is
SELECT * FROM data // select first
WHERE ID = 1
ORDER BY Score DESC// Order by at last
Check http://dev.mysql.com/doc/refman/5.7/en/select.html
And for second case you need to fetch Username inside while loop and use $row['Username'] instead $row[1]['Username']
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "Result = '".$row['Username']."''";// write inside while loop
}
You can assign row value to any array and use that array.
<?php
include "l_connection.php";
$sql = "SELECT * FROM data ORDER BY Score";
$result = mysqli_query($conn, $sql);
if($result->num_rows>0){
$rows = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$rows[] = $row;
}
echo "Result = '".$rows[1]['Username']."'";
}
?>
Or if you want only second highest score from column you can user limit as
$sql = "SELECT * FROM data ORDER BY Score limit 1,1";

How to extract values from single database column / store in array

I am hoping someone can help me with this. I am trying to extract all the values from a single column of a database and store the returned values in a numeric array.
$num = 1;
$q = "SELECT `uninum` FROM `participants` WHERE `islecturer` = '".$num."'";
$result = #mysqli_query ($dbcon, $q);
$storeArray = array();
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
$storeArray [] = $row['uninum'];
}
echo $storeArray [1];
The second parameter to mysqli_fetch_array sets the array type. You have set it to a numerical index. You want an associative index:
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { //correct flag
$storeArray [] = $row['uninum'];
}
Or just use the mysqli_fetch_assoc function instead:
while ($row = mysqli_fetch_assoc($result)) {
$storeArray [] = $row['uninum'];
}

Adding to an array from $row

How do I add each result from $row to the $valueIDArray? I then want to use the $valueIDArray to get results from a second database, how do I do that?
$sql = "SELECT * FROM venue
WHERE capacity >= 'partySize'";
//step 2 - executing the query
$result =& $db->query($sql);
if (PEAR::isError($sql)) {
die($result->getMessage());
}
while($row = $result -> fetchrow()){
$valueIDArray = $row[0];
}
You should do it this way:
$valueIDArray = array()
while($row = $result -> fetchrow()){
$valueIDArray[] = $row[0];
}
Define array before loop, and in loop simple add elements to array using [] after array name
$sql = "SELECT * FROM venue WHERE capacity >= 'partySize'";
//step 2 - executing the query
$result =& $db->query($sql);
if (PEAR::isError($sql)) {
die($result->getMessage());
}
$valueIDArray = array();
while($row = $result -> fetchrow()){
$valueIDArray[] = $row[0];
}
You have to add the [] braces. Like this, you always add another entry for the row.

Categories