Saving while results into an array - php

I am trying to query a database with a new 'WHERE (AND)' clause on each loop. The new clause is simply the number of the loop.
I need to save the count of rows returned per loop in an array which I am struggling with.
If for instance there is two loops, the first loop returns 2 rows, the second 3. I want the array to essentially be:
$portfolio_list = array(2,3);
Here is as far as I have managed to get, and no surprise its not working correctly.
Any help would be great!
$portfolios = 2;
$i = 1;
$portfolios_list = array();
while ($i <= $portfolios) {
$portfolio_sql = "
SELECT COUNT(portfolio_number) AS portfolio_uploaded_images
FROM exp_submissions
WHERE member_id = $member_id
AND type_id = '1'
AND portfolio_number = $i
";
$query = $this->EE->db->query($portfolio_sql);
$return = $query->result();
$portfolios_list[] = $return;
$i++;
}

please try this
$portfolios = 2;
for ($i = 1; $i < $portfolios+1; $i++) { //this runs 2 times
$where_array = array('member_id' => $member_id, 'type_id' => '1', 'portfolio_number' => $i);
$this->db->where( $where_array );
//$this->db->select('*'); // I guess you do not need select for this
$portfolio_list[$i] = $this->db->get('exp_submissions')->num_rows();
}
var_dump($portfolio_list);

Try this
$portfolios = 2;
$i = 1;
while ($i <= $portfolios) {
$portfolio_sql = "
SELECT COUNT(portfolio_number) AS portfolio_uploaded_images
FROM exp_submissions
WHERE member_id = $member_id
AND type_id = '1'
AND portfolio_number = $i
";
$query = $this->db->query($portfolio_sql);
$portfolios_list[$i] = $query->num_rows; // This will give the No of rows fetched
$i++;
}
foreach($portfolios_list as $row => $no)
{
echo "The Results Fetched from query no ".$row." is ".$no;
}

Related

Get name for the differentiating values in two arrays

I need to compare to arrays (mysqli_fetch_array) from the same table fetching all columns.
I'm for-looping through and comparing all results.
$rowA = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM table WHERE ID = '$ID'"));
Performing UPDATE
$rowB = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM table WHERE ID = '$ID'"));
$len = count($rowA);
for($i = 0; $i < $len; $i++){
if($rowA[$i] != $rowB[$i]){
$msg .= [COLUMN NAME] . ' => ' . $rowB[$i];
}
}
How do I get the name of the column that differs?
I've tried array_keys() but the array it outputs isn't useful in ways I can come up with.
So I got this to work for me.
$arr = array_diff_assoc($rowA, $rowB);
$key = array_keys($arr);
$len = count($arr);
for($i = 0; $i < $len; $i++){
$msg .= $key[$i] . ' => ' . $rowB[$key[$i]];
}
Note: Added MYSQLI_ASSOC as resulttype for the mysqli_fetch_array function.

array + array on each iteration of the while

How do I add an array to another? I mean addition, not to add the elements at the end of the array. I have a while structure and I want it to add the values at each iteration.
Tried a few variants like $final_array += $final_array; but I couldn't find a solution and I don't really know how to spell it to find something on SO/Google.
Here is the code:
<?php
$i = 0;
while ($i < 10){
$i++;
$sql = "SELECT * FROM parteneri WHERE nr_intrebare = '$i' AND varianta_raspuns = '$intrebare_01'";
$result = mysqli_query($con, $sql);
$final_array = array();
while ($row = mysqli_fetch_array($result))
{
$final_array[] = $row;
}
}
Edit:
To clear things up, I have a questionnaire that has 10 <select> fields. Here is an example:
<select name="intrebare_01">
<option selected="true" disabled="disabled">Selecteaza o optiune...</option>
<option value="A">Fotbal</option>
<option value="B">Tenis</option>
<option value="C">Basket/Handbal/Hockey/Volei</option>
<option value="D">Alte sporturi</option>
</select>
As you can see, each option has a value ranging from A to D.
I have a table called "parteneri" that contains the points of each of these values for each question. If you need the value in points of the question 4 answer B you can find it there.
The "parteneri" (partners) table has the following structure:
As you can see, there is a numeric value for each option for each of the seven partners.
What I need to do is to add the points each of these partners gathered after processing all of the 10 <select> and display the first three that got the most points.
Please ask if you have any questions that I didn't covered.
As per as i understood you question that you want to add the values of each $final_array to another.
Hope this will be helpful to u :)
<?php
$i = 0;
$array_sum=[];
while ($i < 10){
$i++;
$sql = "SELECT * FROM parteneri WHERE nr_intrebare = '$i' AND varianta_raspuns = '$intrebare_01'";
$result = mysqli_query($con, $sql);
$final_array = array();
while ($row = mysqli_fetch_array($result))
{
$final_array = $row;
$array_sum = array_map(function () {
return array_sum(func_get_args());
}, $array_sum, $final_array);
}
}
?>
Here have an example of this concept
<?php
$c=[];
$b = array(array(1, 20, 11, 8, 3),
array(10, 2, 5, 10, 0),
array(10, 2, 5, 10, 0),
array(10, 2, 5, 10, 0),
array(10, 2, 5, 10, 0));
foreach($b as $key => $value){
$c = array_map(function () {
return array_sum(func_get_args());
}, $c, $value);
}
print_r($c);
?>
Output of this following example
Array ( [0] => 41 [1] => 28 [2] => 31 [3] => 48 [4] => 3 )
Try to use this code:
$i = 0;
$final_array = array();
while ($i < 10){
$i++;
$sql = "SELECT * FROM parteneri WHERE nr_intrebare = '$i' AND varianta_raspuns = '$intrebare_01'";
$result = mysqli_query($con, $sql);
$j = 0;
while ($row = mysqli_fetch_array($result))
{
$final_array[$i][$j] = $row;
$j++;
}
}
<?php
$final_array = array();
$i = 0;
while ($i < 10){
$i++;
$sql = "SELECT * FROM parteneri WHERE nr_intrebare = '$i' AND varianta_raspuns = '$intrebare_01'";
$result = mysqli_query($con, $sql);
$small_array = array();
while ($row = mysqli_fetch_array($result))
{
$small_array[] = $row;
}
$final_array[] = $small_array;
}
Something like this you mean?
If you are trying to add the rows found by your query to $final_array, initialize the $final_array outside both loops.
You could also improve the run time and Security by using a prepared parameterised query here, prepare once and execute many times, so the database only has to compile, optimize and prepare an execution plan once rather than once per iteration.
<?php
$sql = "SELECT *
FROM parteneri
WHERE nr_intrebare = ?
AND varianta_raspuns = ?";
$stmt = $con->prepare($sql);
$final_array = array();
$i = 0;
while ($i < 10){
$i++;
$stmt->bind_param('is', $i, $intrebare_01);
$stmt->execute();
while ($row = stmt->fetch_assoc()) {
$final_array[] = $row;
}
}
print_r($final_array);
And if you dont really need all the columns in your process, replace SELECT * with a SELECT of specific columns, this will also improve runtime and memory usage

Php to Excel : fill the output Excel file with a loop

I want to create an Excel file (with PhpExcel) and fill it with the content of a MySQL query.
I only have one column so the result will look like this :
$sheet->setCellValueByColumnAndRow(0, $i, $content)
So I have to loop inside my query and create a counter to fill each row corresponding to each item of the column ptlum of my content.
So the goal is to have the following result :
1 AX001
2 AX003
3 AX012
The code is the one :
$column = 1;
while($data = mysql_fetch_assoc($result)) {
$workbook = new PHPExcel;
$sheet = $workbook->getActiveSheet();
$sheet->setCellValueByColumnAndRow(0, $column, $data['ptlum']);
//echo($column. " " . $data['ptlum']. " ");
$column = $column + 1; //or $column++;
The problem is that my Excel file is empty..
If i put a number instead of $column in the setCellValueByColumnAndRow line it works. But the variable does not work..
On the other hand if I put "$column = 1;" inside the loop, my Excel file will always contain one only row..
Have you an idea ?
Thank you very much !
You just have to change the call to setCellValueByColumnAndRow for each column and increment it:
$sql = "SELECT ptlum FROM `ptlum` WHERE nomcom = 'AIGREFEUILLE' and RIGHT (date,4) < 2015 and RIGHT(date,4) > 0 ";
$result = mysql_query($sql);
$row = 1; // 1-based index
$column = 1;
while($data = mysql_fetch_assoc($result)) {
$sheet->setCellValueByColumnAndRow($column, $row, $data['ptlum']);
$column = $column + 1; //or $column++; if you prefer
}
As you see, you can retrieve the field/column you want with mysql_fetch_assoc, returning an associative array.
Also, you don't have to include the field(s) of your WHERE condition(s) in the SELECT.
Then finally, you should replace the deprecated mysql_* function by their equivalents mysqli_*, as explained here.
Edit:
For your "new" problem, this code should work:
$sql = "SELECT ptlum FROM `ptlum` WHERE nomcom = 'AIGREFEUILLE' and RIGHT (date,4) < 2015 and RIGHT(date,4) > 0 ";
$result = mysql_query($sql);
$row = 1; // 1-based index
$column = 1;
$workbook = new PHPExcel;
$sheet = $workbook->getActiveSheet();
while($data = mysql_fetch_assoc($result)) {
$sheet->setCellValueByColumnAndRow($column, $row, $data['ptlum']);
$column = $column + 1; //or $column++; if you prefer
}
First, don't instanciate your workbook and sheet in each loop, do it before, once.
Second, you had your arguments in the wrong order, it's column then row, not the inverse, as explicited in the method name.
Maybe this is the thing you wanted:
$sql = "SELECT ptlum, RIGHT(date,4) FROM `ptlum` WHERE nomcom = 'AIGREFEUILLE' and RIGHT (date,4) < 2015 and RIGHT(date,4) > 0 ";
$result = mysql_query($sql);
$i = 0;
while($data = mysql_fetch_assoc($result)) {
$sheet->setCellValueByColumnAndRow(0, $i, $i+1); //1-based index
$sheet->setCellValueByColumnAndRow(1, $i, $data['ptlum']);
$i++;
}

How to merged 3 arrays in one line output in php [duplicate]

This question already has answers here:
Two arrays in foreach loop
(24 answers)
Closed 6 months ago.
Good Day!
Any suggestions on how can I merged and print 3 arrays in PHP.
I retrieved data from database and put it in ARRAY.
1st Array: $date[] = $row['date'];
2nd Array: $requestor[] = $row['requestor'];
3rd Array: $die[] = $row['die'];
then I use foreach to print the retrieved data stored from each Array that meets the condition.
foreach($date as $item_date){
echo $item_date;
}
foreach($requestor as $item_requestor){
echo $item_date;
}
foreach($die as $item_die){
echo $item_requestor;
}
But the result of this code is like this:
date1
date2
date3
requestor1
requestor2
requestor3
die1
die2
die3
My goal is this one:
date1 - requestor1 - die1
date2 - requestor2 - die2
date3 - requestor3 - die3
Any Idea oon how can I achieved this output.
TIA
You have to do it manually count on loop like this
$count = count($date)-1;
then loop through this
for ( $i=0;$i <= $count; $i++ ) {
$arrayGenerate[$i] = array(
'row1' => $data[$i].'-'.$requestor[$i].'-'.$die[$i]
);
}
like this
Try with -
for($i = 0; $i <= count($date); $i ++) {
echo $date[$i]." - ".$requestor[$i]." - ".$die[$i];
}
Assuming the all 3 arrays count/size is same & you want it in this fashion
<?php
$a = array('1','2','3');
$b = array('4','5','6');
$c = array('7','8','9');
for($i=0;$i<count($a);$i++)
{
echo $merged_arr_str = $a[$i] . " - " . $b[$i] . " - ". $c[$i] . " <br/>";
}
?>
You can try this
Example One:-
$date = array('date1','date2','date3','date4');
$requestor = array('requestor1','requestor2','requestor3','requestor4');
$die = array('die1','die2','die3','die4');
$count = max(count($date), count($requestor), count($die));
$newarray = array();
for($i=0; $i < $count; $i++) {
//Demo1
if (isset($date[$i])) $newarray[] = $date[$i];
if (isset($requestor[$i])) $newarray[] = $requestor[$i];
if (isset($die[$i])) $newarray[] = $die[$i];
//Demo2
//echo $ouput = $date[$i].'-'.$requestor[$i].'-'.$die[$i];
}
//array merge output
var_dump($newarray);
Example Two
$date = array('date1','date2','date3','date4');
$requestor = array('requestor1','requestor2','requestor3','requestor4');
$die = array('die1','die2','die3','die4');
$arrays = array($date, $requestor, $die);
array_unshift($arrays, null);
$n = call_user_func_array('array_merge', call_user_func_array('array_map', $arrays));
print_r($n);
for($i = 0; $i < count($date); $i ++) {
echo $date[$i]." - ".$requestor[$i]." - ".$die[$i];
}
this loop will iterat untill last element of date array.if you want to put equal to sign then you have to initialize $i with 1.
exm. if $i = 0 then $i < count($date)
OR
if $i = 1 then $i <= count($date)

Get value from SQL database

I am trying to get a series of 'titles' from a database, and place them in an array as individual strings for each title. Currently I am using this code
mysql_select_db($database_Algorox_Build, $Algorox_Build);
$query_getLatest = "SELECT title FROM news ORDER BY title ASC";
$getLatest = mysql_query($query_getLatest, $Algorox_Build) or die(mysql_error());
$totalRows_getLatest = mysql_num_rows($getLatest);
$latestNews = array();
for ($i = 0; $i <= $totalRows_getLatest; ++$i) {
$row_getLatest = mysql_fetch_assoc($getLatest);
$latestNews[] = array_values($row_getLatest);
}
and when I call them individually using
echo $latestNews[0][0];
I get the string value.
However, I would like to place these strings in to a single array, thereby generating an array of strings. I have tried this:
$latestNews = array();
$extractNews = array();
for ($i = 0; $i <= $totalRows_getLatest; ++$i) {
$row_getLatest = mysql_fetch_assoc($getLatest);
$latestNews[] = array_values($row_getLatest);
$extractNews[] = $latestNews[i][0];
}
but it doesn't return the string in the output extractNews array.
What am I doing wrong?
Thanks
Is this what you are looking for?
mysql_select_db($database_Algorox_Build, $Algorox_Build);
$query_getLatest = "SELECT title FROM news ORDER BY title ASC";
$getLatest = mysql_query($query_getLatest, $Algorox_Build) or die(mysql_error());
$latestNews = array();
while($row = mysql_fetch_assoc($getLatest)) {
$latestNews[] = $row['title'];
}
echo "<pre>" . print_r($latestNews,1) . "</pre>";
WATCH OUT
Please do not use the mysql_* functions anymore. They are deprecated and won't be supported in >= php 5.5. Switch to mysqli_* or PDO.

Categories