PHP Replace specific values inside formula - php

I have a formula where some of the data needs to be replaced by MYSQLI query results.
The formula can look like:
100+400-600-700
The numbers in the formula will match a specific table line in the DB and output correct value, for example:
121000+1000-8000-2000
I've tried to extract all the special characters from the original string in order to get the correct DB result via MYSQLI using formula:
preg_match_all('!\d+!', $rf, $matches);
foreach ($matches as $key1 => $value) {
//Declare summarization of TOT rows
$TOT = 0;
foreach ($value as $single) {
$querymatch = mysqli_query($mysqli, "SELECT rowMainAccount FROM reportTable_rowDefinitions WHERE rowCode = '$single' AND reportID = $rowDefinition");
$arraymatch = mysqli_fetch_array($querymatch);
$TOTaccount = $arraymatch['rowMainAccount'];
//Fetch values from FinancialTransactions
//Fetch values
$queryTOT = mysqli_query($mysqli, "SELECT SUM(debit) AS debitTOT, SUM(credit) AS creditTOT FROM FinancialTransactions WHERE mainAccount = $TOTaccount AND entity = $org AND date BETWEEN '$newStartDate' AND '$newEndDate'");
$arrayTOT = mysqli_fetch_array($queryTOT);
$TOTcred += $arrayTOT['creditTOT'];
$TOTdeb += $arrayTOT['debitTOT'];
}
$TOT += $TOTdeb - $TOTcred;
}
echo $TOT; //Returns values
This will only replace the numbers in the original string giving result as
121000100080002000
from foreach loop.
How can I put the returned values from DB into the original formula to acieve the correct output as
121000+1000-8000-2000
?

Use preg_replace_callback and in the callback you can get the appropriate value and return it to place it in the original string.

Related

Calculation error with Numbers containing more than 3 Digits

I'm importing prices from a database using the following code:
//implode items, turn into string
$item_implode = join("','", $item_array);
//declare an overall array for result
$product = array();
$result = $mysqli->query("SELECT Name, WPrice as price, APrice as a_price from my_table where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode');");
while($row = $result->fetch_assoc()) {
$product_name = $row['Name'];
// find all keys in $item_array which value is the products
$keys = array_keys($item_array, $product_name);
foreach ($keys as $key) {
// add values for these keys
$product[$key + 1]["Name"] = $row['Name'];
$product[$key + 1]["price"] = number_format($row['price'],2);
$product[$key + 1]["a_price"] = number_format($row['a_price'],2);
}
}
And then I apply the following functions:
function price($m) {
global $product,$i;
if ($m == "a") {
$value = $product[$i]["a_price"];
}
else {
$value = $product[$i]["price"]; //
}
return $value;
}
I'm trying to use the following comparison:
<?php if ( price( a )< price( default ) ) {echo "Smaller";} ?>
To echo Smaller whenever the price of A is smaller than the default price.
It works fine for prices in the range of 0 to 999.99, but for when a price of 1,000 or more is involved, I'm getting the opposite results (it echos smaller when bigger and vice-versa)
What is causing this problem?
You're comparing strings because that's what you stored in $product["price"] and $product["a_price"] (the function number_format() returns a string value). For numbers >= 1000, those strings include commas, which breaks the comparison.
Compare the numeric values and don't call number_format() until you need to display the values.

Removing data from MYSQL that is comma delimited via Get and php

What I am doing is adding values to a mysql table with each value seperated by a comma. And each new value is appended to that last value once again seperated by a comma. Now this is all dynamic. What I am having an issue is on how to remove a selected value and the comma. I am using php and mysql.
I can read the values out with explode and line[value].
table name is values
table consist of id, value, value_array
$value_selected would be a $_GET['value']
value_array is the column that contains all the values seperated by comma.
The database selects from values where the id is equal to the Get value.
Then returns all values in the value_array
I then explode the values and have each value from the value_array read through the for loop and line[value].
the code:
start php
$value_selected = $_GET['value'];
$query = mysql_query("SELECT * FROM values WHERE id='$value_selected'");
while($result = mysql_fetch_assoc($query))
{
$check_values = $result['value_array'];
}
$values = explode(",",$check_values);
$count_values = count($values);
for($counter = 0; $counter < $count_values; $counter++)
{
$line = each($values);
$query = mysql_query("SELECT * FROM values WHERE id='$line[value]'");
while($result = mysql_fetch_assoc($query))
{
echo $result['value'].'<br/>';
}
}
php end
I don't have an issue reading it out. What I'm trying to do is being able to select a value via GET and remove that value from the value_array while also removing the trailing comma. I hope I was able to expalin in more detail my issue.
Use a foreach loop, take the exploded string and reassemble it minus the string $value_selected by doing this:
$NewValue = '';
$i = 1;
foreach ($values as $Value) {
if ($i > $count_values) {
break;
} else {
if ($Value !== $value_selected) {//reassemble comma-sep string - $_GET['value']
$NewValue = $NewValue . $Value . ",";
}
}
$i++;
}
Now $NewValue no longer contains $_GET['value'], because the concatenation in the if statement only occurs when the exploded fragment $Value does not match $_GET['value']. Update the database or echo $NewValue, etc. as necessary at this point.

How to iterate through database results, compare each value to that in an array and return the matching id?

I am trying to build a function that will be given an array. and from this array, iterate through an entire table in the database trying to find a match. If it does find a match. I would like it to echo out the ID of that match from the database table.
If possible I would also like it to say if it found any close matches?
What's making this tricky for me is that it needs to match all values despite their order.
for example, if the function is given this array:
$array = array(1,2,3,4,5)`
and finds this array in the database:
$array = array(2,3,5,1,4)
it should consider this a match
Also, if it finds
array(1,2,3,4,5,6)
It should output this this as a match except for value 6.
Let me refrase your question, is this correct?
Based on an array of ID's, return all records whose ID's are in the array.
If so, use the IN operator:
SELECT *
FROM tableName
WHERE columnName IN (value1, value2, value3, etc.)
So first we need to transform the given array into a comma-seperated list:
$comma_seperated = implode(', ', $array);
Now we have a comma-seperated list we can use in our query:
$comma_seperated = implode(', ', $array);
$query = "SELECT *
FROM tableName
WHERE id IN (" . $comma_seperated . ")";
// execute query, don't use mysql_* functions, etc. ;)
You could use any of the options:
option 1:
$array = array(1,2,3,4,5);
$query = "SELECT id FROM youtable WHERE id IN(".implode(",",$array).")";
option 2:
$array = array(1,2,3,4,5);
$query = "SELECT id FROM yourtable";//Select ids
Now iterate through query results, say results are stored in $query_results,
$result=array();
foreach($query_results as $row){
if(in_array($row['id'],$array)){
$result[] = $row['id'];
}
}
You can use array difference to get the result just run the code and you will understand
Case 1
$array1 = array(1,2,3,4,5);
$array2 = array(1,2,3,4,5,6);
$result = array_diff($array1, $array2);
print_r($result);
Case 2
$array1 = array(1,2,3,4,5);
$array2 = array(1,2,3,4,5,6);
$result = array_diff($array2, $array1);
print_r($result);
And after that you can the count of $result and put it in your logic.
Case 1:
Maybe you can select the unique values from the database.
SELECT DISTINCT unique_values_that_need_for_compare_column FROM table
This SQL result will be the $databaseValues variable value.
Than iterate through the array that the function gets.
foreach ($functionArray as $value) {
if (in_array($value, $databaseValues)) {
// you have a match
echo $value;
}
}
Case 2:
Or you can make a query for every value:
foreach ($functionArray as $value) {
$query = "SELECT COUNT(*) as match FROM table WHERE unique_values_that_need_for_compare_column = " . intval($value);
// fetch the result into the $queryResult variable and than check
if ($queryResult['match']) {
// you have a match
echo $value;
}
}

How to order this array to High to Low? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to sort the results of this code?
I have made this code which allows a user to type in a search bar a question. This code then takes that question and looks for watching words with questions in my database. It then counts the number of matching words for each question. Once done it then displays the top 4 best matched questions depending on how many words match.
However at the moment it displays these matches from lowest word match to highest word match (low-to-high) and I was it the other way around so that it displays the best match first (high-to-low). How do I do this in this code?
<?php
include("config.php");
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING); //User enetered data
$search_term = str_replace ("?", "", $search_term); //remove any question marks from string
$array = explode(" ", $search_term); //Seperate user enterd data
foreach ($array as $key=>$word) {
$array[$key] = " title LIKE '%".$word."%' "; //creates condition for MySQL query
}
$q = "SELECT * FROM posts WHERE " . implode(' OR ', $array); //Query to select data with word matches
$r = mysql_query($q);
$count = 0; //counter to limit results shown
while($row = mysql_fetch_assoc($r)){
$thetitle = $row['title']; //result from query
$thetitle = str_replace ("?", "", $thetitle); //remove any question marks from string
$title_array[] = $thetitle; //creating array for query results
$newarray = explode(" ", $search_term); //Seperate user enterd data again
foreach($title_array as $key => $value) {
$thenewarray = explode(" ", $value); //Seperate each result from query
$wordmatch = array_diff_key($thenewarray, array_flip($newarray));
$result = array_intersect($newarray, $wordmatch);
$matchingwords = count($result); //Count the number of matching words from user entered data and the database query
}
if(mysql_num_rows($r)==0)//no result found{
echo "<div id='search-status'>No result found!</div>";
}
else //result found
{
echo "<ul>";
$title = $row['title'];
if ($matchingwords >= 4){
?>
<li><a href='<?php echo $row['url']; ?>'><?php echo $title ?><i> No. matching words: <?php echo $matchingwords; ?></i></a></li>
<?php
$count++;
if ($count == 5) {break;
}
}else{
}
}
echo "</ul>";
}
?>
If you have saved you data in an array you can simply reverse it by using http://www.php.net/manual/en/function.array-reverse.php
Otherwise there are some sort functions
http://php.net/manual/en/function.sort.php
I think you have problem in sorting an array.
If you have an array, sorting is not a matter.
Having different types of sorting found in php.
arsort()
Sort an array in reverse order and maintain index association
http://www.php.net/manual/en/function.asort.php
You can use this array function or let me know your questions briefly.
you can write a own filter function
// sorts an array by direction
function arr_sort($arr, $index, $direction='asc')
{
$i_tab = array();
foreach ($arr as $key => $ele)
{
$i_tab[$key] = $arr[$key][$index];
}
$sort = 'asort';
if (strtolower($direction) == 'desc')
{
$sort = 'arsort';
}
$sort($i_tab);
$n_ar = array();
foreach ($i_tab as $key => $ele)
{
array_push($n_ar, $arr[$key]);
}
return($n_ar);
}
for example you have an array $arr = array('key' => 'value', 'key2' => 'value');
you can now sort by key2 asc with
$arr = arr_sort($old_arr, 'key2', 'desc');
so you can put the total count of matching words into your array as a node for any entry and filter it by it descending
note this requires Mysql version 4+
A fulltext sql query returns values based on relevance.
Example:
SELECT *, MATCH (title)
AGAINST ('$search_term' IN NATURAL LANGUAGE MODE) AS score
FROM posts;
This is how you would implement it
$q = "SELECT *,MATCH (title) AGAINST ('$search_term' IN BOOLEAN MODE) AS relevancy FROM
posts WHERE MATCH (title) AGAINST ('$search_term' IN BOOLEAN MODE) ORDER BY
relevancy DESC";
This will return the posts in order by relevancy. May need to remove the '' around $search_term but you can figure that out with testing.
Please read up on Fulltext sql queries and the match() function. It is all clearly documented.

Getting total percentage inside while loop

For example I have a mysql_num_rows results of 4,8,15,16,23,42 in a query that is inside a while loop of another query. My question is how can I get the percentage per each result of mysql_num_rows inside my while loop? Example: 4,8,15,16,23,42. Total is 108. $sum = 108. Percentage of 4 = 4/$sum = 3.7%, 8 = 8/$sum = 7.4% and so on..
you can store all the values in an array and do the calcs after you have retrieved the data from the database
eg
$datastore = array();
$total = 0;
while(list($amount) = mysql_fetch_row($result)) {
$datastore[] = $amount;
$total += $amount;
}
foreach ($datastore as $amount) {
echo $amount," - ";
printf("%5.2f", $amount/$total);
echo "\r\n";
}
$values = array(4, 8, 15, ...);
$sum = array_sum($values);
foreach($values as $value) {
echo ($value / $sum) * 100;
}
CodePad.
So you are saying that you want the $sum before the individual results right? You could do a simple additional query to get the sum before you pull out the individual results. Use the SUM aggregate function. It is probably also possible to get the percentage in your SQL results. That would mean a slightly more complex query, but not an additional query.

Categories