Removing data from MYSQL that is comma delimited via Get and php - 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.

Related

PHP Replace specific values inside formula

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.

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.

I need a counter within a counter

I have searched for this, can't find it and it should be simple, but now I'm crosseyed. Forgive me - I've only been at this for a few months.
I need a counter within a counter in php, such that I pair $Id1 with $Id2, then $Id3, then $Id4, etc. for a single loop through, and then for the second loop pair $Id2 with $Id3, then $Id4, then $Id5 etc. I get the Ids from a sql query, then I use both of them to run a calculation of their relationship, but first I just need the structure to run these two loops, one within the other. Thanks for any help and your patience.
Edited to add what I have so far:
$collection = [];
$sql = 'SELECT id, name FROM table';
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result))
{
$collection[] = $row;
}
$ct = count($collection);
for ($i = 0; $i < $ct; $i++)
{
$Id1 = $collection[$i]['id'];
for ($j = 0; $j < $ct; $j++)
{
$Id2 = $collection[$j]['id'];
if($Id1 != $Id2){
echo 'IDs: ' . $Id1 . ' ' . $Id2 . '<br>';
}
}
}
}
If you fetch the IDs from your query into an array like this: $ids = [1,2,3,4,5,6,7,8];, you can get a list of pairs using array_chunk, then shifting off the first element, and repeating this process until the array is empty.
while ($ids) { // repeat until empty
$pairs = array_chunk($ids, 2); // split into pairs
foreach ($pairs as $pair) {
if (count($pair) == 2) { // verify that you have a pair (last element will
// have only one item when count($ids) is odd)
var_dump($pair); // do something with your pair of IDs
}
}
$remove_first = array_shift($ids); // shift off the first ID
}
Please note that using array_shift like this will destroy your input array, so if you need to do something else with it as well, make a copy of it before using this approach.

php sum the values seperated by special character

I need to sum the result set values separated by "|" inside the loop eg. set of values 10|2, 6|2, 8|1 should result in 24|5.
here is my code:
<?php
$fromdate="2016-03-31";
$todate="2016-03-31";
$TAG="1";
$con = mysqli_connect("XXXXX","XX","XXX","XXX");
$query = mysqli_query($con, "CALL sp_Android_Online_Dashboard('$fromdate', '$todate','$TAG')") or die("Query fail: " . mysqli_error());
$Totfiles = 0;
$file_minutes = 0;
$Tot_minutes=0;
$Pending=0;
while(($row = mysqli_fetch_array($query)))
{
$Totfiles +=$row["Totfiles"];
$file_minutes +=$row["file_minutes"];
$Pending =str_replace(array("/"),"|",$row["Pending"]); //need to sum all the values separated by "|"
$Tot_minutes +=$row["Tot_minutes"];
}
$response["Details"]['Totfiles'] = $Totfiles;
$response["Details"]['file_minutes'] = $file_minutes;
$response["Details"]['Pending'] = $Pending;
$response["Details"]['Tot_minutes'] = $Tot_minutes;
echo json_encode($response);
?>
$row["Pending"] contains the values which are to be summed
result am getting now,
"Pending":"16|9"
"Pending":"11|3"
"Pending":"6|2"
my expected result,
"Pending":"33|14"
This is what you are aiming at i think, you make an array first containing 2 values, on each iteration through the loop you add the new values to them and at the end you can implode it into a string again
// Start with an array containing 0 twice
$Totalpending = [0,0];
while(($row = mysqli_fetch_array($query)))
{
// On each loop we add the left value to the first value in the array and the right value to the second value in the array
$tmp = explode("|", $row['Pending']);
$Totalpending[0] += $tmp[0];
$Totalpending[1] += $tmp[1];
$Totfiles +=$row["Totfiles"];
$file_minutes +=$row["file_minutes"];
$Pending =str_replace(array("/"),"|",$row["Pending"]); //need to sum all the values separated by "|"
$Tot_minutes +=$row["Tot_minutes"];
}
// if you want to format the values in the same way again, although an array is much easier to handle, but it's up to you.
$stringTotalpending = implode('|',$Totalpending);
the string value you want will then be in $stringTotalpending
So Firstly, we need to explode the values from $row["Pending"].
$arr = explode("|", $row["Pending"]);
Now use a loop to add those two numbers:
$temp = 0;
for($i = 0; $i < count($arr); $i++){
$temp += (int) $arr[$i];
}
Now the $temp would contain the result.
As simple as that.
And also as a side note, your code is vulnerable to SQL-Injection attacks.
What about evaling the same string with '|' replaced by '+' ?
eval('$result = ' . str_replace('|', '+', preg_replace('/[^0-9|]/', '', $row["Pending"])) . ';');
echo "$result\n";
Note preg_replace() to sanitize input. Can be avoided if input is already sanitized

How to extract comma separated column values from database using php

In my database table there is a column named 'marks' . it contains values like 50,55,67,88,...
Now I need to read this values one by one like - first 50, then 55 and so on. How is it possible using php ?
include("db_connect.php");
$result = mysql_query("SELECT * FROM students ",$con);
while($rows = mysql_fetch_array($result))
{
$mark1=$rows['marks'];//what will do here
$mark2=$rows['marks']; //should get value 55 and so on
}
If your values are comma separated then explode the field.
http://php.net/manual/en/function.explode.php
include("db_connect.php");
$result = mysql_query("SELECT * FROM students", $con);
while($rows = mysql_fetch_array($result)) {
$mark=explode(',', $rows['marks']);//what will do here
foreach($mark as $out) {
echo $out;
}
}
Explode the data from the database. Use the explode function.
Access using indexes
while($rows = mysql_fetch_array($result)) {
$marks = $row['marks']; //get value of marks from the database
$exp = explode("," , $marks); //explode marks data
$mark1 = $exp[0]; //result is 50
$mark2 = $exp[1]; //result is 55
$mark3 = $exp[3]; //result is 67
}
Or loop using foreach
while($rows = mysql_fetch_array($result)) {
$marks = $row['marks']; //get value of marks from the database
$exp = explode("," , $marks); //explode marks data
foreach($exp as $mark) {
echo $mark;
}
}
If that row contains ,, the just use explode():
while($rows = mysql_fetch_assoc($result)) {
$mark1 = explode(',', $rows['marks']); // should contain the comma separated values
// in array form
// then loop again
foreach($mark1 as $mark_piece) {
// do something here
}
}
You should use the explode function
$marks = explode(",", $rows['marks']);
foreach($marks as $mark){
//your code to do something with the mark.
}
N.B. explode() function breaks the string into array, it accepts three arguments, first one is the delimiter that specifies where to break the string, second one is the string that needs splitting, and third one is not mandatory but it tells how many array to return.
$str_to_exploade = 'This,string,needs,some,exploiting';
$explode_string = explode(',', $str_to_exploade);
echo '<pre>';
print_r($explode_string);
echo $explode_string[0].'<br/>';
echo $explode_string[1];
More about explode() go to : http://php.net/manual/en/function.explode.php

Categories