PHP foreach loop running one extra time - php

I am having a bit of trouble with this for loop here and hope to get some help !
So I will recreate a simplified version of the loop here:
foreach($quote as $key => $item) {
if(isset($item['dbid'])){
$q_sql = new mysql_builder2('quote',3);
} else {
$q_sql = new mysql_builder2('quote',2);
}
$q_sql->addArgument('name', $name);
$q_sql->addArgument('curr', $curr);
foreach($term[$key] as $data) {
if(isset($data['term_id']) {
$t_sql = new mysql_builder2('details',3);
} else {
$t_sql = new mysql_builder2('details',2);
}
$t_sql->addArgument('date', $date);
$t_sql->addArgument('term', $termnum);
mysqli_query($dbc, $t_sql->build());
}
mysqli_query($dbc, $q_sql->build());
}
Okay, so I think I got it all right here.
EDIT: Before the loops I have the following :
$quote = $_POST['quotes'];
$term = $_POST['terms'];
Inside the HTML the name of these elements is structured like so:
quotes[1][name]
quotes[1][curr]
terms[1][1][date]
terms[1][1][termnum]
and then if there's a second:
quotes[2][name]
quotes[2][curr]
terms[2][1][date]
terms[2][1][termnum]
terms[2][2][date]
terms[2][2][termnum]
etc..
Explaination:
First, mysqli_builder2 is a premade function that creates SQL queries.. When the value is 3, it sets UPDATE, when it's 2 it does INSERT
Now, what will happen is a user will fill out a form and the data will go into two tables, Quote and Details. For each single entry into Quote, there can potentially be multiple in Details (note: I've left out a lot of fields in my example code to save space but there are links between the 2 tables).
My problem here is when I run this for a very simple UPDATE, the second foreach loops runs one extra time always, and it is always an INSERT with random values for each field.. I can't seem to figure why this is happening because it works 100% properly for the first foreach loop..
Example array output when submit:
Array
(
[0] => UPDATE quote SET job_id = 2, wo_id = 9952, quote_num = '1a', revenue = '100.00', cost = '100.00', currency = 1, term = 1 WHERE id = 5857;
)
Array
(
[0] => UPDATE details SET user_id = 532, job_id = 2, wo_id = 9952, quote_num = '1a', percent = 10, term = 1, active = 1, status = 0, date_picked = '2015-02-04', date_submitted = now() WHERE id = 588;
[1] => INSERT INTO details(user_id, job_id, wo_id, quote_num, percent, term, active, status, date_picked, date_submitted) VALUES(532, 2, 9952, '1a', 6, 6, 1, 0, '1969-12-31', now());
)
This INSERT should not be there at all (notice the date going in) ..
Anyways, I'm kind of stuck here and any help is appreciated. If you need any other info just ask :)
Thanks !

Are you sure you copy the code as is?
you have got syntax error:
if(isset($data['term_id']) {
should be:
if(isset($data['term_id'])) {

Related

PHP & MySQL: While Loop

first, i am pretty new to PHP and MySQL, so i still code precedurally.
I am working on an application that takes transactions and pays out a due amount at a certain maturity date to users who have previously made a donation. i have a function knapSolveFast2 that solves the knapsack problem (where a set of transaction amounts in a database adds up to a due amount for a users who's maturity date is up). currently, my demo database looks like this:
if my current date (now) = 2017-04-03 11:36:03 = CAST(NOW() AS DATETIME), my application is meant to loop through the database, fetch users whose maturity_date is >= 1 month from tran_date (i.e. WHERE maturity_date <= CAST(NOW() AS DATETIME) ). Take each user found and pair them for payment in a while loop to other users tran_amt in the database whose tran_amt sums up to the maturity users found due_amount using the knapsack function knapSolveFast2.
Question:
after finding the user with maturity date due for payment (2 users) with the first while loop, i am trying to run an inner while loop to pair each user to other users whose tran_amt sums up to the fetched user's due amount. the problem here is, the inner while loop only runs for the first user found an not for thesecond user.
The code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$connect = #mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno()) {
die("<pre><h1>Sorry, we are experiencing a little Downtime!</h1></pre>");
}
//include the match controller containing the knapSolveFast2 function
include('controller/match.php');
//UPDATE `pendingpair`SET `maturity_date`= DATE_ADD(`tran_date`, INTERVAL 1 MONTH)
//select user to be paid
$sql = "SELECT `user_id`, `due_payment` FROM `pendingpair` where `maturity_date` <= CAST(NOW() AS DATETIME) ORDER BY `id` ASC";
$queryRun = mysqli_query($connect, $sql);
$num_rows = mysqli_num_rows($queryRun);
if ($num_rows > 0) {
while ($row = mysqli_fetch_assoc($queryRun)) {
$user_id_due = $row['user_id'];
$user_amt_due = $row['due_payment'];
print_r($row);
/* Perform queries to select users to pay $user_id_due the sum of $user_amt_due; Where:
- user to be paid, $user_id_due, is not included in the pairing logic
- transacton payment to be chosen, ph_conf = 1, has been confirmed
- transaction has not yet been paired for payment, tran_paired_status = 0
- transactions have not been flaged for fake POP (proof of Payment), `ph_denied_fpop`= 0
*/
$fetchQuery = "SELECT `tran_inv`, `tran_amt`, `user_id` FROM `pendingpair`WHERE `tran_amt` <= {$user_amt_due} && `user_id` != {$user_id_due} && `ph_conf`=1 && `tran_paired_status` = 0 && `ph_denied_fpop`=0 ORDER BY `id`";
$m = array(); // Match Memo items array
$picked_trans = array();
$numcalls = 0; // number of calls made to get Match
$tran_inv = array();
$tran_amt = array();
$user_id = array();
//run query and throw users that fit the criteria into an array
if ($queryRun = mysqli_query($connect, $fetchQuery)) {
//check if data was pulled
if (mysqli_num_rows($queryRun) != NULL) {
//grab data from array and insert it into an array
while ($row = mysqli_fetch_assoc($queryRun)) {
//Populate Arrays to be used
$tran_amt[] = $row['tran_amt'];
$tran_inv[] = $row['tran_inv'];
$user_id[] = $row['user_id'];
}
}
}
## Solve
list ($m4,$pickedItems) = knapSolveFast2($tran_amt, $tran_amt, sizeof($tran_amt) -1, $user_amt_due, $m);
# Display Result
echo "<b><br><br>Invoice:</b><br>".join(", ",$tran_inv)."<br>";
echo "<b>Tran Amt:</b><br>".join(", ",$tran_amt)."<br>";
echo "<b>User_id:</b><br>".join(", ",$user_id)."<br>";
echo "<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>";
}
}
?>
the result of the first while loop that finds user with the proper maturity date criteria is:
Array
(
[user_id] => 9
[due_payment] => 150
)
Array
(
[user_id] => 2
[due_payment] => 150
)
this means 2 users are due. but on trying to loop these users. the match for the second user is never found... only that of the first user is.
Array
(
[user_id] => 9
[due_payment] => 150
)
Invoice:
1102, 9022, 9113, 9029, 9116
Tran Amt:
100, 50, 100, 50, 50
User_id:
2, 5, 8, 5, 7
Max Value Found:
150 (in 19 calls)
Please help me figure out what i am missing. Thaaaaank you :)
Your problem is that you call the variables the same thing.
If you look at :
while ($row = mysqli_fetch_assoc($queryRun)) //External loop
Inside that loop you have another
while ($row = mysqli_fetch_assoc($queryRun)) //Internal loop
So the variables inside the external loop, you are using for the internal loop are essentially overwriting the External loops variables, and thus when it is time for the second run of your External loop, the code think it is done, since it is refering to the internal loops variable
To fix this, you must rename the variables you use for the internal loop
Note SECOND_ for both the queryRun and the row
Try this:
if ($SECOND_queryRun = mysqli_query($connect, $fetchQuery)) {
//check if data was pulled
if (mysqli_num_rows($SECOND_queryRun) != NULL) {
//grab data from array and insert it into an array
while ($SECOND_row = mysqli_fetch_assoc($SECOND_queryRun)) {
//Populate Arrays to be used
$tran_amt[] = $SECOND_row['tran_amt'];
$tran_inv[] = $SECOND_row['tran_inv'];
$user_id[] = $SECOND_row['user_id'];
}
}
}

Iterating through PHP array with duplicate records and deleting one record where a value = 0

I have a MySQL query using Laravel that I convert to a PHP Array.
The rows have values similar to this:
name | override | percentage
Eclipse | 1 | 50%
Eclipse | 0 | 75%
MySQL query
select * from table
Both rows (it's many more than just 2 in reality) have the same name, but one has override set to 0 and one has it set to 1.
How can I get rid of all records in my query result (PHP array) that are duplicates (determined by the name) AND have override set to 0? I want only the records that have been overridden with a new record which I have done, but I need a way to remove the records with override = 0, given that the records are the same but have a different percentage value.
How can this be done?
Thanks.
Try following query,
SELECT * from testtable GROUP BY `name` HAVING count(`name`) = 1 OR `override` = 1;
check this sqlfiddle
If I understand your needs correctly, you need to filter out records that have duplicate name and override = 0.
If you sort your result set by name (SELECT * FROM TABLE ORDER BY name), you can use this function.
function removeDuplicatesFromArray($rows) {
$result = array();
$old_name = '';
foreach($rows as $row) {
if($row['name'] != $old_name) {
$result[] = $row;
$old_name = $row['name'];
}
elseif($row['override'] == 1) {
array_pop($result);
$result[] = $row;
}
}
return $result;
}
NOTE: Doing this in SQL will be WAYYYYYYYYY faster and use far less memory. I would only try this PHP approach if you cannot modify the SQL for some reason.
Maybe try out... hit the db twice, first time only get non-overrides, then get the overrides in second pass -- coerce your arrays to be indexed by name and array_merge them. (Uses a fair chunk of memory given the number of arrays and copies - but it's easy to understand and keeps it simple.
$initial = get_non_overridden();
$override = get_overridden();
$init_indexed = index_by_name($initial);
$over_indexed = index_by_name($override);
$desired_result = array_merge($init_indexed, $over_indexed);
Assuming your database gives you a standard rowset (array of rows, where each row is a hash of fields->values). We want something that looks like this instead:
[
'Eclipse' => [
'name' => 'Eclipse',
'override' => '0',
'percentage' => '75%'
],
'Something' => [
'name' => 'Something',
'override' => '0',
'percentage' => '20%'
],
]
So index_by_name would be:
function index_by_name($rowset) {
$result = array();
foreach ($rowset as $row) {
$result[ $row['name'] ] = $row;
}
return $result;
}
There are ways to tweak your efficiency either in memory or run time, but that's the gist of what I was thinking.
array_merge then overwrites the initial ones with the overridden ones.
NOTE: this all assumes that there is only one row where Eclipse override is 1. If you have twenty Eclipse|0 and one Eclipse|1, this will work, if you have two Eclipse|1 you'd only see one of them... and there's no way to say which one.

json DataTable in googlecharts

I am having a bit of trouble getting the proper format of json string.
I have a database table that looks something like this:
Table Columns: emp month sales
Table rows: Bob 1 100
Bob 2 150
Jane 1 125
Jane 2 130
Mary 1 110
Mary 2 130
Within drawChart(), I can create something like this statically:
var data = google.visualization.arrayToDataTable([
['Month', 'Bob', 'Jane', 'Mary],
['Jan', 100, 125, 110],
['Feb', 150, 130, 130]
]);
In the end, the json string needs to look like this:
{"cols":[{"label":"Month","type":"string"},
{"label":"Bob","type":"number"},
{"label":"Jane","type":"number"},
{"label":"Mary","type":"number"}],
"rows":[{"c":[{"v":100},{"v":125},{"v":110}]},
{"c":[{"v":150},{"v":130},{"v":130}]}]}
But I am having trouble pulling from the table to come up with proper json formatting that is equivalent to the above. I am following the steps from here... PHP MySQL Google Chart JSON - Complete Example
But that example is only for a single data set. if you were to add multiple weeks instead of having just one data set, how do run the query?
To get your data in the format you want, you have to pivot your data. Some databases support pivotting, but others like MySQL don't. If you are stuck without pivot support, then you have to resort to trickery to make it happen. Here's one way you could do it:
SELECT
month,
SUM(if(employee = "Bob", sales, 0)) AS Bob,
SUM(if(employee = "Jane", sales, 0)) AS Jane,
SUM(if(employee = "Mary", sales, 0)) AS Mary
FROM myTable
GROUP BY month
This requires that you know ahead of time what the employee names are so that you can write the SQL statement (either when you write the code, or you could pull them from another SQL query and write a dynamic SQL query).
Asgallent, thank you. Your response gave me the direction I needed. I was able to do it all dynamically via SQL. I made two queries: 1 to the "saleperson" table to get the names, and then another to pivot the data as you suggested. For anyone else that might find this helpful, here is the code I have.
The queries (Note: I am using codeigniter):
$sp_qry = $this->db->query('select * from salespeople');
$qryString="";
foreach ($sp_qry->result_array() as $row)
{
$qryString.= ",SUM( IF( `salespeople_id` =" . $row['salespeople_id'] . ", `num_sold` , 0 ) ) AS " . $row['name'];
}
$qry= "SELECT `month` " . $qryString . " FROM `product_sales`
GROUP BY `month`";
$query = $this->db->query($qry);
return $query->result_array();
and in my viewing page
$rows = array();
$table = array();
$cols = array();
$cols[] = array('label' => 'Month', 'type' => 'string');
foreach ($salespeople as $sp)
{
$cols[] = array('label' => $sp['name'], 'type' => 'number');
}
$table['cols'] = $cols;
foreach ($sales as $chart_item)
{
$tmp=array();
$tmp[] = array('v' => (string) $chart_item['month']);
foreach ($salespeople as $sp)
{
$name=$sp['name'];
$tmp[] = array('v' => (int) $chart_item[$name]);
}
$rows[] = array('c' => $tmp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);

Specifying conditions on database results to array

In my database I have a field called "modules" - info data looks like this: 1, 4, 1, 3
I want to list/output all data via PHP with the numbers 1 - all other numbers have to be ignored.
I want to check the output result via an array NOT via mySQL
Any suggestion how I can do that?
$list_modules = array();
$res_m = $db->Execute("SELECT modules FROM users u WHERE user_id = '".$user->id."'");
while ( $m = $res_m->GetNext() ) {
$list_modules = array($m['modules']);
}
print_r($list_modules); //Output below
Example (Output):
Array
(
[0] => 1, 4, 1, 3
)
You can do that in you MySQL with a WHERE clause. Depending on the column name in the database:
SELECT column_name FROM table WHERE column_name = 1;
Note: In your question it looks like you tried to list a range:
with the numbers 1 - all other numbers have to be ignored.
If you meant to put a range (e.g. 1 - 4) then your WHERE clause would be:
WHERE column_name BETWEEN 1 AND 4
You should test for that in your MySQL query:
SELECT * FROM `TABLE` WHERE `modules` = 1;
Or, alternatively, if that's not possible..
Loop with foreach and test for 1?
$array = array(1,4,1,3);
foreach ($array as $element) {
if ($element == 1) { echo 1; }
}
This should do it... there is really no other way seeing at the col is Varchar, you also need to eliminate strings like 15, 21, etc. so %1% will not work.
SELECT modules FROM users WHERE user_id = ".$user->id." AND modules LIKE % 1,%
Give it a shot and let me know if it works.
You stated in your comment that the modules field contains comma-separated values, is that right? I reckon that the modules field is VARCHAR, CHAR, or any other string. If so, you could use a query like:
SELECT * FROM `tableName` WHERE `modules` LIKE '%1,%';
There may be other solutions, probably more optimal, but this one should perform well, I think.
Meh found the solution I could use.
$list_modules = array();
$query = "SELECT modules FROM users WHERE user_id = ".$user->id."";
$res_m = $db->Execute($query);
while ( $m = $res_m->GetNext() ) {
$list_modules = array('id' => $m['modules']);
}
$modules = explode(",",$list_modules['id']);
foreach ($modules as $key => $value) {
if($value == 1){
// list data
}
}
}

How can I select a PHP variable that relates to a specific percentage chance?

I'm trying hard to wrap my head around what I'm doing here, but having some difficulty... Any help or direction would be greatly appreciated.
So I have some values in a table I've extracted according to an array (brilliantly named $array) I've predefined. This is how I did it:
foreach ($array as $value) {
$query = "SELECT * FROM b_table WHERE levelname='$value'";
$result = runquery($query);
$num = mysql_numrows($result);
$i=0;
while ($i < 1) {
$evochance=#mysql_result($result,$i,"evochance"); // These values are integers that will add up to 100. So in one example, $evochance would be 60, 15 and 25 if there were 3 values for the 3 $value that were returned.
$i++;
}
Now I can't figure out where to go from here. $evochance represent percentage chances that are linked to each $value.
Say the the favourable 60% one is selected via some function, it will then insert the $value it's linked with into a different table.
I know it won't help, but the most I came up with was:
if (mt_rand(1,100)<$evochance) {
$valid = "True";
}
else {
$valid = "False";
}
echo "$value chance: $evochance ($valid)<br />\n"; // Added just to see the output.
Well this is obviously not what I'm looking for. And I can't really have a dynamic amount of percentages with this method. Plus, this sometimes outputs a False on both and other times a True on both.
So, I'm an amateur learning the ropes and I've had a go at it. Any direction is welcome.
Thanks =)
**Edit 3 (cleaned up):
#cdburgess I'm sorry for my weak explanations; I'm in the process of trying to grasp this too. Hope you can make sense of it.
Example of what's in my array: $array = array('one', 'two', 'three')
Well let's say there are 3 values in $array like above (Though it won't always be 3 every time this script is run). I'm grabbing all records from a table that contain those values in a specific field (called 'levelname'). Since those values are unique to each record, it will only ever pull as many records as there are values. Now each record in that table has a field called evochance. Within that field is a single number between 1 and 100. The 3 records that I queried earlier (Within a foreach ()) will have evochance numbers that sum up to 100. The function I need decides which record I will use based on the 'evochance' number it contains. If it's 99, then I want that to be used 99% of the time this script is run.
HOWEVER... I don't want a simple weighted chance function for a single number. I want it to select which percentage = true out of n percentages (when n = the number of values in the array). This way, the percentage that returns as true will relate to the levelname so that I can select it (Or at least that's what I'm trying to do).
Also, for clarification: The record that's selected will contain unique information in one of its fields (This is one of the unique values from $array that I queried the table with earlier). I then want to UPDATE another table (a_table) with that value.
So you see, the only thing I can't wrap my head around is the percentage chance selection function... It's quite complicated to me, and I might be going about it in a really round-about way, so if there's an alternative way, I'd surely give it a try.
To the answer I've received: I'm giving that a go now and seeing what I can do. Thanks for your input =)**
I think I understand what you are asking. If I understand correctly, the "percentage chance" is how often the record should be selected. In order to determine that, you must actually track when a record is selected by incrementing a value each time the record is used. There is nothing "random" about what you are doing, so a mt_rand() or rand() function is not in order.
Here is what I suggest, if I understood correctly. I will simplify the code for readability:
<?php
$value = 'one'; // this can be turned into an array and looped through
$query1 = "SELECT sum(times_chosen) FROM `b_table` WHERE `levelname` = '$value'";
$count = /* result from $query1 */
$count = $count + 1; // increment the value for this selection
// get the list of items by order of percentage chance highest to lowest
$query2 = "SELECT id, percentage_chance, times_chosen, name FROM `b_table` WHERE `levelname` = '$value' ORDER BY percentage_chance DESC";
$records = /* results from query 2 */
// percentage_chance INT (.01 to 1) 10% to 100%
foreach($records as $row) {
if(ceil($row['percentage_chance'] * $count) > $row['times_chosen']) {
// chose this record to use and increment times_chosen
$selected_record = $row['name'];
$update_query = "UPDATE `b_table` SET times_chosen = times_chosen + 1 WHERE id = $row['id']";
/* run query against DB */
// exit foreach (stop processing records because the selection is made)
break 1;
}
}
// check here to make sure a record was selected, if not, then take record 1 and use it but
// don't forget to increment times_chosen
?>
This should explain itself, but in a nutshell, you are telling the routine to order the database records by the percentage chance highest chance first. Then, if percentage chance is greater than total, skip it and go to the next record.
UPDATE: So, given this set of records:
$records = array(
1 => array(
'id' => 1001, 'percentage_chance' => .67, 'name' => 'Function A', 'times_chosen' => 0,
),
2 => array(
'id' => 1002, 'percentage_chance' => .21, 'name' => 'Function A', 'times_chosen' => 0,
),
3 => array(
'id' => 1003, 'percentage_chance' => .12, 'name' => 'Function A', 'times_chosen' => 0,
)
);
Record 1 will be chosen 67% of the time, record 2 21% of the time, and record 3 12% of the time.
$sum = 0;
$choice = mt_rand(1,100);
foreach ($array as $item) {
$sum += chance($item); // The weight of choosing this item
if ($sum >= $choice) {
// This is the item we have selected
}
}
If I read you right, you want to select one of the items from the array, with some probability of each one being chosen. This method will do that. Make sure the probabilities sum to 100.

Categories