Storing formatted variable into MySQL DB? - php

I had this working by simply passing the data from one variable to another like so:
$CalcsSets = $DisplayCalcs;
without the need to use the loop inside the first if() statement and it inserted the data without quotes but all of a sudden it's stopped working and I'm not sure why (it only started showing last integer), so I went with the more complex code trying to get it to work again as shown below.
Here's the complex code I'm working with:
for($i=1; $i<=$CalcSets; $i++){
$calculations = PerformCalc($min, $highest, $OperatorType);
echo 'Calculations performed for '.$SetText[$i];
foreach ($calculations as $key => $DisplayCalcs) {
echo $SetCalc[] = $DisplayCalcs.', '; //stores calculations with ',' in
//array.
}
if($CalcSets == 1){
for($i=0;$i<$CalcSets;$i++){
$SetResults = $SetCalc[$i];
echo '<strong>'.(string)$SetResults.'</strong>';
}
DB_Insert($SetResults);
}
What it's supposed to do is insert values in the following format (1,2,3,4,5,) into the database in a VARCHAR row but now all it shows is the last integer with no comma. I originally wanted to just store the integers and not a comma but I couldn't get it to display on the page with commas after each integer so I went this route as mentioned earlier.
I realize I'm probably going about this the wrong way, but if any of you know a much easier, and shorter, way to do what I want, I'd be extremely appreciative of the help.
Reason I'm doing it this way, is because on the results page, it needs to show in the format mentioned above.
FYI, I did check the DB row and it is still set to VARCHAR with a length of 10 at the moment.
UPDATE TO MAKE INTENTIONS MORE CLEAR
Ok, I'm going to go back to square one and try to make my intention as clear as possible. I've been rewriting this code snippet more times than I care to count and my brain is all foggy lol.
array1 = array(1, 2, 3, 4, 5, 6);
foreach(array1 as $key => $data){
echo $data.',';
// will display 1,2,3,4,5,6, in browser.
}
if(is_true == 1){
INSERT ALL $data values into DB here.
}
That's what I'm trying to accomplish in it's simplest form, I'm just have extreme difficulty achieving my goal.
Second Update - Topic Solved
Apparently, the DB field had to be set to Text rather than VarChar. I guess we learn something new everyday.
Again, thanks everyone for all of your help. It was greatly appreciated!

I'm sorry but I couldn't make much sense from the original code but focusing only on the last IF and the containing LOOP, I think the problem is with the assignment statement:
$SetResults = $SetCalc[$i];
It should instead use .= for concatenation. Here is how it should look:
if($CalcSets == 1){
for($i=0;$i<$CalcSets;$i++){
$SetResults .= $SetCalc[$i];
echo '<strong>'.(string)$SetResults.'</strong>';
}
DB_Insert($SetResults);
}
Hope it works!
I completely agree with the solution from #KemalFadillah for using the implode() method. From your code snippet, I understand that $calculations is the array that stores the main values, i.e. Array(1, 2, 3, 4, 5). So you can do:
$calculations = PerformCalc($min, $highest, $OperatorType);
$s = implode (', ', $calculations);
DB_Insert($s);
I hope that makes sense?

You are executing the last for loop only if $calcSets == 1 and have an $i<$calcSets condition
How about doing it like this
$SetCalc = "";
foreach ($calculations as $key => $DisplayCalcs) {
 echo $SetCalc .= $DisplayCalcs.', ';
}
DB_Insert("(".$SetCalc.")");

You're looking for the implode() function to format the numbers.
$formatted = implode(',', $calculations); // Produce 1,2,3,4,etc...
http://php.net/manual/en/function.implode.php

Related

How do you set up an array to hold '0's for empty locations so graphs(Highcharts) can format them correctly?

I'm trying to get my Highcharts graph to work. The Reason I'm having so much trouble with it this time is because I have to keep the program adaptable for future changes when it comes to my columns(named issues1 through 12).
The Goal is pretty simple, I just need to grab the issues between hours 1-12 during a certain time period, then create a graph.
My idea Is that I should create a view that organizes the desired information because there is a lot more to that table that I left out, and then create an SQL to organize the data from there. Which I realize might be overkill, but I'm an intern and my supervisor probably did it to help make it simple for me.
There are 4 different places I need to use SQL to make the Table work.
X-Axis
Day shift numbers
Swing shift numbers
Night shift numbers
So for my code The X-Axis, It works fine for just calling in the names.
xAxis: {
categories: [
<?php
foreach ($xAxisresult as $Xrow) {
echo "'" . $Xrow['IssueName'] . "'" . ',';
}
?>
]
I believe the Day/Swing/Grave SQL statements should all be similar so I'm just going to focus on one. But this is where the problem starts with how I have it set up. I tried to run an If statement were I compare the two arrays I have set up and try to match the IssueName Columns.
name: 'Day',
data: [
<?php
foreach ($Dresult as $Drow) {
if ($Xrow['IssueName'] == $Drow['IssueName']){
echo $Drow['Issues'] . ',';
}
else{
echo $Drow['Issues'] . ',';
}
}
You guys can most likely see a lot of whats wrong here. But I need to make a loop or array that will find out that if there is an empty spot in the array and output a 0 so the data stays correct.
Sorry for the wall of Text, I just wanted to give you guys as much information as possible.
To answer your question how to create an array that holds zero values and merge with the data array (I assume).
You can use array_fill to create the array with zeros, and use array_replace to replace with the data array.
$arr = array_fill(0, 10, 0); //[0,0,0,0,0,0,0,0,0,0]
$data = [2 => 15, 5 =>10, 7 => 16]; // your data
$new = array_replace($arr, $data);
var_dump($new); // [0,0,15,0,0,10,0,16,0,0]

Create a string from a fetch(PDO::FETCH_ASSOC)

I am trying to build a string made of the results from sql and I do not know how achieve this when the data from the db is bigger than 1.
I was able to do it when the result from the database is one.
$result = $stmt_grade->fetch(PDO::FETCH_ASSOC);
$str ="[{$result['score_access']}, {$result['score_training']},
{$result['score_expectation']}, {$result['score_total']} ]";
but when I needed to loop the fetch_assoc I was not able to assign a value to variables or directly build the string.
while ($resultcount = $stmt_count->fetch(PDO::FETCH_ASSOC)){
$resultcount['subarea'];
}
I have looked everywhere and did not find any solutions or any similar approach to find inspiration. I hope someone can help me. Thank you in advance!
The most obvious way to do this is loop through all of the responses in a while loop, and continually append to your string using the .= operator. You can tell when you run out of records because $result will be false.
I separated each record with a newline. It also looked like you wanted to count results, so I added that, too.
$str = ""; // start with an empty string
$count = 0;
while ( ($result = $stmt_grade->fetch(PDO::FETCH_ASSOC)) !== false ) {
// increment the record count
$count++;
// add a new line to the output string
$str .= "[{$result['score_access']}, {$result['score_training']},{$result['score_expectation']}, {$result['score_total']} ]\n";
}
That should do it.
All you need is to name your string properly.
And then use a proper way to create a JSON string. Which consists of two parts:
Create a array of desired structure. Or at least provide a that structure here to let us to provide you with the code.
Use json_encode().
Assuming you need a nested array like this
[[1,2,3],[1,2,3],[1,2,3]]
the code would be
$result = $stmt_grade->fetchAll(PDO::FETCH_NUM);
echo json_encode($result);
thanks for all the answers provided without you I could not made it. Finally, I achieved the desirable result as follow, probably it is not elegant but works:
$stmt_count= $user->countbyespeciality();
while ($resultcount = $stmt_count->fetch(PDO::FETCH_ASSOC)){
$prueba.= "{$resultcount['subarea']},";
$prueba2.= "{$resultcount['number']},";
}
$string=rtrim($prueba, ",");
$string2=rtrim($prueba2, ",");
$final="[{$string}]";
$final2="[{$string2}]";
The output is [something,something] [1,2,] as expected.
thanks again!

Variable pulled from DB not working in a function

Cannot get my head around why a variable pulled from a db is not working.
I have an array that I am searching using array_search().
Using the function like so:
$band2 = taxBandtoPrice2("$car->tax_band");
echo "(£$band2 Per Year)";
Note, "$car->tax_band" is a query that takes the tax_band value. This part works for a certain.
$band2 is always blank. If i replace "$car->tax_band" with 'c' it works fine.
How should I be doing this where might I be going wrong?
The function itself:
function taxBandtoPrice2($taxband){
$bands = array(
0 => 'a',
1 => 'b',
...
);
$key = array_search($taxband, $bands);
return $key;
}
Looking at the code it should work. You can try following changes:
$band2 = taxBandtoPrice2($car->tax_band);
echo "(£{$band2} Per Year)";
Ensure with var_dump($car->tax_band) and later with var_dump($band2) what values and types are. What can I think off are two reasons:
$car->tax_band is not equal to values in $bands. Even a single
space and lower/uppercase makes difference.
List item $car->tax_band gets
overwritten before passed to function.
Simple fix for me on this one.
I was passing in a C but the values in my array were in lower case...
I changed the value to a lowercase with
strtolower();

Get values from 2 rows of a table and combine them as a string

I'm trying to get 2 fields from 2 rows of a table and combine them to be a string. For example:
username id text
row 1 Jason 1 ......
row 2 Lass 2 ......
Basically I would need to get $usernames=Jason, Lass.
What I've tried:
$username_raw=$this->db->select('username')->get('user', 2);
foreach ($username_raw->result() as $row):
echo $username
endforeach;
But the last 3 rows turned out not to be working and i'm kinda stuck here. Any advice is appreciated.
Stab in the dark tells me this is a CodeIgniter question - you should tag that so people know how your query is working. Anyway, your $username variable is not initialized. You'll need to access it by $row->username.
I suggest you add the usernames to an array, then implode() the results:
$username_raw=$this->db->select('username')->get('user', 2);
$usernames = array();
foreach ($username_raw->result() as $row):
$usernames[] = $row->username;
endforeach;
$your_usernames_combined = implode(', ', $usernames);
echo $your_usernames_combined; // e.g. Jason, Lass
If you want the period at the end like your example, add $your_usernames_combined .= '.'; to the end.
Assuming you're using the Codeigniter framework, you need to use $row->username instead.
Then you need to use an array to store the usernames.
I would probably use the "sprintf" function, and the code will look like this
$username = sprintf("%s, %s",$value1,$value2);
Your question is pretty unclear, and i dont completely understand where you make calls to your MySQL database, i can only see you calling for the 2nd username

PHP Calculation in variables from foreach output

I have this code:
$fookerdos = '';
foreach (glob("records/*/*/kerdos.txt") as $somekerdos) {
$fookerdos .= file_get_contents($someposoA);
//to print them i you want
print $fookerdos;
So my problem that for this code will outputs many numbers becouse of many files.
for example will out output this
3.5 -6.7 6.68 -0.2 and so on..
now i want all this numbers to make them (addition)
i know how to addition some 2-3 variables, but i additions many numbers that I even dont know how many they are.
for example
print "3.5 + "-6.7" "6.68" "-0.2";
Thx :)
Does each file contain only a single number, or can they have more than one numbers?
From your previous edits, it seems as if one file contain only a number.
In that case, you can store the values in an array and sum the numbers using array_sum() or perform any other calculation as needed.
Here is a sample code for you:
$fookerdos = array ();
foreach (glob("records/*/*/kerdos.txt") as $somekerdos) {
$fookerdos[] = file_get_contents($somekerdos);
}
echo array_sum ($fookerdos);

Categories