Hi I'm am sure this is a silly mistake but I have been staring at this the past 20mins to
no avail. I have an array balance[] that is populated with two values for balance[0]
and balance[1]. These are populated within the first for loop however when I go to use these values outside after this the array balance[0] is empty.
Below is my code and output:
for ($i=0; $i<$counter; $i++){
$x = mysql_query("
SELECT `outputValue` FROM `output` WHERE `outputType`= 'balance' && `period`= '6' && teamID = '$ID[$i]'
")or die($x."<br/><br/>".mysql_error());
// set ID's = to a variable and now get Outputs for each variable(teamID)
$balance = array();
$row = mysql_fetch_assoc($x);
echo $i." = I<br/>";
$balance[$i] = $row['outputValue'];
echo "Team ".$i."Balance = ".$balance[$i]."<br/>";
}
for ($i=0; $i<$counter; $i++){
echo "Team ".$i."Balance = ".$balance[$i]."<br/>";
}
You're initializing the $balance inside of the loop. On each for loop iteration, the $balance value is rewritten with an empty array().
On the first iteration, the $balance is set to an empty array, and then the $balance[0] is set.
On the second iteration, the $balance is set to an empty array again, and then the $balance[1] is set.
So, after the loop, the $balance will only contain one element at the index of $counter-1.
Move the line
$balance = array();
outside of the loop.
Related
I have a few problems with my code. I can't get the variable status value outside the For statement. I tried to echo it and it's doing nothing.
Here is my code:
public function handlequiz()
{
$datetime = Date("Y-m-d, h:m:s");
$parameter = DB::table('parameter')->first();
$countchoice = $parameter->multiplechoice;
$customer_answer = new CustomerAnswer;
for ($i=0; $i <= $countchoice; $i++)
{
$radio = Input::get('radio'.$i);
$status = DB::table('quiz_answers')->where('answerid', '=', $radio)->lists('status');
}
$answerimplode = implode(";", $status);
$customer_answer->email = Input::get('email');
$customer_answer->cust_id = Input::get('id');
$customer_answer->multiplechoice = $answerimplode;
$customer_answer->save();
return Redirect::to('quiz')->with('message', FlashMessage::DisplayAlert('Your answer has been submitted.', 'info'));
}
I tried to vardump $status inside for it return me an array so I implode it. But outside for{} it returns nothing.
Is there any suggestion to fix this?
Your for loop is overwriting the $status variable every iteration. Therefore, if the last iteration doesn't find a status value, your $status variable will be an empty array, which when imploded, gives you an empty string.
I'm assuming that quiz_answers.answerid is supposed to be unique, and you're trying to get the one status for each of the radio selections. If your quiz_answers query should only be returning one record per answerid, you're probably looking for the pluck() method, not the lists() method.
$status = array();
for ($i=0; $i <= $countchoice; $i++)
{
$radio = Input::get('radio'.$i);
// add the 'status' value to the $status array
// pluck gets the value of the field from the first result, whereas
// lists would return an array with the value from all the results
$status[] = DB::table('quiz_answers')->where('answerid', '=', $radio)->pluck('status');
}
// use array_filter to remove any empty values in the $status array
$answerimplode = implode(";", array_filter($status));
As optimization, use whereIn function
radios = array();
for ($i=0; $i <= $countchoice; $i++)
$radios[] = Input::get('radio'.$i);
$status = DB::table('quiz_answers')->whereIn('answerid',$radios)->lists('status');
$answerimplode = implode(";", $status);
I am trying to run a query off multiple array variables and display the results in a table.
The user selects 1 or more records, which includes BOL and CONTAINER. These selections are put in their own arrays and they are always an equal amount.
<?php
$bolArray = explode(',', $_POST['BOL']);
$containerArray = explode(',', $_POST['CONTAINER']);
$count = count($bolArray); // to get the total amount in the arrays
I use a FOR loop to separate each value from the 2 arrays:
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
}
Here is the part where I'm stuck and probably where I am messing up.
I need to take each variable from the FOR loop and run query using both variables.
First, I'll start the table:
echo "<table><thead><tr><th>BOL</th><th>Container</th></thead><tbody>";
Here is where I tried a FOREACH loop:
foreach($containerArray as $container) // I am not sure if I am using this FOREACH correctly
{
And now, the query. Please take note of the variables from the first FOR loop:
$preQuery = "SELECT * FROM mainTable WHERE CONTAINER = '".$container."' AND BOL = '".$bol."'";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
I use a WHILE loop with a mysql_fetch_assoc:
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>'
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '<td>'.$preRow[ANOTHER_COLUMN].'</td>';
echo '</tr>'
}
}
echo '</tbody></table>';
?>
The query actually works. Problem is, it only returns 1 record, and it's always the last record. The user could select 4 records, but only the last record is returned in the table.
I tried to use the same query and paste it inside the first FOR loop. I echoed out the query and it displayed the same amount of times as the number of array values, but will only return data for the last record.
I do not understand what I am doing wrong. I just want to display data for each value from the array.
Edit
Here is what the code looks like when I throw the query in the first FOR loop:
echo "<table class='table table-bordered'><thead><tr><th>BOL</th><th>Container</th></tr></thead><tbody>";
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
$preQuery = "SELECT BOL_NUMBER, CONTAINER_NUMBER FROM `intermodal_main_view` WHERE BOL_NUMBER = '". $bol ."' AND CONTAINER_NUMBER = '".$container."'";
$preRes = mysql_query($preQuery) or die();
$preNum = mysql_num_rows($preRes);
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>';
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '</tr>';
}
}
echo "</tbody></table>";
I think you can use "IN" if your POST vars are comma separated.
$preQuery = "
SELECT * FROM mainTable
WHERE CONTAINER IN ($_POST['CONTAINER'])
AND BOL IN ($_POST['BOL'])
";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
Then go to your while loop....
This would omit the need for creating an array and looping it.
Also, you need to switch to PDO for your query, and switch to parameter binding. It will take all of an hour to learn.
I'm trying to make a tag cloud system getting its values from PHP/SQL but it seems to work erratically, only giving a handful of the expected results. What's causing this odd behaviour?
As far as I can tell it should loop through a total of 20 times (0-19) and each time it adds a string into an array.
The system starts out by getting the 20 most popular tags from my database in descending order, once its got this I create a string and set the font size. This string is then stored in an array and is echoed out using a random number array giving a random order to the cloud.
I then increase the value of i for my loop iteration whilst decreasing the font size for the next less popular tag.
<h1>Tag Cloud</h1>
<?php
$sql = "SELECT * FROM tags ORDER BY count DESC";
$tags_query = mysqli_query($db_conx, $sql);
$i = 0;
$tag_array = array();
$tag_size_max = 36;
$tag_size_min = 16;
$numbers = range(0, 19);
shuffle($numbers);
do {
$row = mysqli_fetch_array($tags_query, MYSQLI_ASSOC);
$tag = $row["tag"];
$tag_count = $row["count"];
$tag_array[] = "<p style='font-size:".$tag_size_max."px; padding:0px;'>".$tag."</p>";
echo $tag_array[$numbers[$i]];
$i++;
$tag_size_max--;
} while ($i < 20);
?>
You can see it kind of working in the footer of my site http://www.vwrx-project.co.uk
It seems that you're trying to echo $tag_array element with index which isn't yet in the array itself.
You would probably need two loops - first to fill the $tag_array, and another one to echo them.
Do you have proper ERROR_LEVEL - there should be some notices about missing indexes - at least if I'm ready your code correctly ;)
Something like this:
// fill the array
for ($i=0; $i<20; $i++) {
$row = mysqli_fetch_array($tags_query, MYSQLI_ASSOC);
$tag = $row["tag"];
$tag_count = $row["count"]; // this seems to be unused
$tag_array[] = "<p style='font-size:".$tag_size_max."px; padding:0px;'>".$tag."</p>";
}
// echo the array
for ($i=0; $i<count($tag_array); $i++) {
echo $tag_array[$numbers[$i]];
}
I think the problem occurs in the following line
echo $tag_array[$numbers[$i]];
when you push to the array
$tag_array[] = "<p style='font-size:".$tag_size_max."px; padding:0px;'>".$tag."</p>";
you get an index for each tag , for example
[0] =>"<p style='font-size:".$tag_size_max."px; padding:0px;'>".$tag."</p>";
[1] =>"<p style='font-size:".$tag_size_max."px; padding:0px;'>".$tag."</p>";
for every iteration
and then in the following line you echo a random element (probably different form the one you just created )from the array by using the $number array which is not ordered after shuffling it.
I suggest you shuffle the results from the database first with
$results = array();
while($row =mysqli_fetch_array($tags_query, MYSQLI_ASSOC))
{
array_push($results, $row);
}
shuffle($results);
and then create a "normal" loop for printing in the tags using the results array.
Also if you need only 20 tags why not adding LIMIT 20 to your query to simplify the code?
Hope it helps
I'm new in php and got stuck doing a loop.
I have the following:
an array containing 0 or not named $receivers.
another array containing total of receivers which is a number, named $totalreceivers.
a function querying a table with the id, returning 0 or number, named status().
I want to loop through each status() of the receivers and show the sum at the end. I couldn't get it.
Any help will be appreciated. Thanks in advance.
Here is what I tried:
for ($i = 0; $i < $totalreceivers; $i++)
{
$status = status($receivers[$i]);
foreach ($totalreceivers as $value)
$status = status($receivers[$i]);
echo "the sum of receiver having status different than 0 is";
echo count($status);
}
function status($id)
{
global $dbhost;
global $dbuser;
global $dbpass;
global $dbname;
global $d1;
$q2 = mysql_query("select * from user where id ='$id' AND subscription_end_date IS NULL", $d1);
while($row2 = mysql_fetch_array($q2))
$rowservice = $row2['value'];
return $rowservice;
}
A couple things in your code don't really make sense. First, you're trying to iterate through $totalreceivers twice, one loop being nested in the other. I doubt that's what you want so you should get rid of one of them. And your first loop has a bad expression: to iterate through $totalreceivers in your first for loop, you need to have your testing expression go against the number of elements in the array and not the array itself (can use count()): for ($i = 0; $i < count($totalreceivers); $i++).
Second, you're resetting the value of $status each time you call status() in your loop. To add to it, use the += operator: $status += status($receivers[$i]);
Third, you're doing the same in status() function with $rowservice; resetting it each iteration of that while loop. Either set it once, or sum it up.
You can simplify this task by letting MySQL do more of the work for you.
You have an array $receivers which presumably contains id's for subscribers to (receivers of) something. (I may use receiver and subscriber interchangeably.)
The status() function retrieves from the database the value for each receiver where the subscription_end_date is null. I am going to assume that there is only one row per subscriber because you only return the last result via the variable $rowservice.
It's unclear from your code if you want a count of receivers with a value other than 0, or if you want a sum of all non-zero values. The question then is:
Do you want to know how many subscribers have nonzero values? or,
Do you want to know the sum of all values for subscribers with nonzero values?
Fortunately both of these can be easily found:
How many receivers have non-zero values?
$allreceivers = implode(',', $receivers);
$query = "SELECT COUNT(id) AS total_receivers
FROM user
WHERE subscription_end_date IS NULL
AND value != 0
AND id IN ($allreceivers);";
$result = mysql_query($query, $d1);
$row = mysql_fetch_array($result);
$total_receivers = $row['total_receivers'];
echo "The number of receivers having status (value) other than 0 is $total_receivers";
What is the sum of all receiver values?
$allreceivers = implode(',', $receivers);
$query = "SELECT SUM(value) AS receiver_value_sum
FROM user
WHERE subscription_end_date IS NULL
AND id IN ($allreceivers);";
$result = mysql_query($query, $d1);
$row = mysql_fetch_array($result);
$receiver_value_sum = $row['receiver_value_sum'];
echo "The sum of receiver values is $receiver_value_sum";
At first glance, it looks like you are just overwriting "$status" on each iteration. Before the loop starts, set $status to an empty array and then add to it on each iteration. For example:
$status = array();
foreach ( $totalreceivers as $value)
{
$status[] = status($receivers[$i]);
}
echo count($status);
I will try to outline some possible problems with your code below:
for ($i = 0; $i < $totalreceivers; $i++) { //This open bracket has no end bracket
/*I assume total receivers is the number of receivers; if that is the case, it shouldn't be an array, but merely a value.*/
$status = status($receivers[$i]);
/*I think you should define the status function before you call it; also, if you are just calling the status function for each value of $receivers, why don't you just do a foreach($receivers as $value) loop, like you did below with $totalreceivers. */
foreach ( $totalreceivers as $value)
/*I'm not sure what $totalreceivers is. You said its an array containing total number of receivers; again, I would think this would be a single value, and not an array*/
{
$status = status($receivers[$i]);
/*looks like you're calling the status function again*/
}
echo "the sum of receiver having status different thant 0 is"; echo count($status);
/* $status at this point would count the value from row2 for the last value in $receivers, and not a count of array values. Perhaps you could do $status[] = status($receivers[$i]), and then count($status) to save each value to an array, then count the elements. */
function status($id){
global $dbhost;
global $dbuser;
global $dbpass;
global $dbname;
/* The values above aren't used in the function; you may want to connect to the database outside of the function, before the foreach loop. */
global $d1 ;
$q2 = mysql_query("select * from user where id ='$id' AND subscription_end_date IS NULL",$d1);
while($row2 = mysql_fetch_array($q2)){
$rowservice = $row2['value'];
}
return $rowservice;
}
/*the rest looks good*/
What I want to do here is to be able to assign the values from sql query into arrays.
And then compute for the total.
<?php
include('conn.php');
$qreports=query_database("SELECT S_PRICE, PID, QTY_PUR, ITEM_ID, CUSID, CNUM, Cust_Name, TDATE FROM prod_table, customer_credit, sales_trans_items WHERE prod_table.PID=sales_trans_items.ITEM_ID AND sales_trans_items.CNUM=customer_credit.CUSID AND sales_trans_items.TDATE='2011-02-06 09:14:09'","onstor",$link);
$grandtotal=0;
$customer="";
while($qrep=mysql_fetch_assoc($qreports)){
$pid=$qrep['PID'];
foreach ($pid as $k => $v) {
$sids=$v;
$qtypur=$qrep['QTY_PUR'][$k];
$sprice=$qrep['S_PRICE'][$k];
$customer=$qrep['Cust_Name'][$k];
$tdate=$qrep['TDATE'][$k];
$stot=$qtypur * $sprice;
$grandtotal =$grandtotal + $stot;
}
}
echo "Customer: ". $customer."<br/>";
echo "Profit: ". $grandtotal;
?>
I tried the query on phpmyadmin before I place it in the code, and it output this:
I think you misunderstood how mysql_fetch_assoc works: Every call returns one row from the result set. $grep is an array with structure columnname => value.
That also means that $qrep['PID'] cannot be an array and your foreach loop won't work. In every loop, $qrep['PID'] contains one of the values you see in the PID column in your screen shot.
I suggest you add print_r($qreq); in your while loop so you get more familiar with the structure of the array.
As each $qrep is an array itself, creating a result array is just adding each of these to a new array:
$result = array();
while(($qrep=mysql_fetch_assoc($qreports))) {
$result[] = $qrep;
}
Now you are performing some more computation where I am not sure what you want to get in the end but it seems you are multiplying each QTY_P with S_PRICE:
$total = 0;
foreach($result as $report) {
$total += $report['QTY_P'] * $report['S_PRICE'];
}
(You could however also compute this in your while loop)
Assuming you want to get the overall sum and the sum for each customer:
$total = 0;
$total_per_customer = array();
foreach($result as $report) {
$customer = $report['Cust_Name'];
if(!array_key_exists($customer, $total_per_customer)) {
$total_per_customer[$customer] = 0;
}
$price = $report['QTY_P'] * $report['S_PRICE'];
$total_per_customer[$customer] += $price;
$total += $price;
}
In the end, $total_per_customer is an array with customer names as keys and the sum of the prices as values. $total will contain the sum of all prices.
You question is a bit unclear, but i think the answer wont be far a way from the following suggested references:
As you loop through the rows use
something like $array[] =
$qrep['columnName'] to populate an
array.
Then, check out PHP's array_sum().