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();
Related
I am trying to fetch values using where() query in yii2, I want to use multiple where conditions from which values will be fetched, I have tried several alternatives none of them seems to work.
The number and contents of $values is varying
$test = Material::find()->where(['Material.MaterialId' => $value])->joinWith(['objectName'])->all();
This one works for single value. But if i do a foreach loop to get all the variation values. So I get a string like
$values = "'ID1','ID2','ID3','IDn',";
$test = Material::find()->where('in', 'Material.MaterialId' , [$values])->joinWith(['objectName'])->all();
It Returns Nothing But If I use is like that
$test = Material::find()->where('in', 'Material.MaterialId' , [ID1','ID2','ID3','IDn',])->joinWith(['objectName'])->all();
This gets me the required results. I have also tried the same using or in where clause and orWhere method, I guess all are having same problem.
Try this way
$value = [' ID1','ID2','ID3','IDn'];
$test = Material::find()->where(['Material.MaterialId' => $value])->
joinWith(['objectName'])->all();
I want to use str_replace te replace some values in a variable and get a variable named $username with the value USERNAME. It works fine for one value but not for multiple values.
This works..
$myabsoluteurl=JURI::current();
$replacestring='http://www.website.com/index.php/component/comprofiler/userprofile/';
$usertemp= str_replace($replacestring, '', $myabsoluteurl);
However there are four possibilities how a url can look so i need 4 variables
$replacestring1='http://www.website.com/index.php/component/comprofiler/userprofile/';
$replacestring2='http://www.website.com/index.php/instellingen/userprofile/';
$replacestring3='http://www.website.com/index.php/component/comprofiler/';
$replacestring4='http://www.website.com/index.php/instellingen';
How can get al four possibilities stripped so i can place the remaining value in a variable? The username is always placed behind one of the four urls...
You can declare $replacestringas an array, and then run a for loop within the array.
$replacestring = array('string1', 'string2');
foreach ( $replacestring as $string ) {
// do stuff
};
I seem to have looked everywhere for this.
Here is the code i use to set a variable to a piece of data from a MySQL database
$PartNo=mysql_result($result,$i,"PartNo");
Where
$result = mysql_query("SELECT * FROM PriceList");
$i = 0, is added to by 1 every time my while loop restarts
PartNo is a field name in my MySQL table and also the name of the variable I want to set the data in the database to
PriceList is my database name
I want to loop through all the field names (the array has them) and set variables with the same names to that data. Like this:
$PartNo=mysql_result($result,$i,"PartNo");
$Group=mysql_result($result,$i,"Group");
$OnHand=mysql_result($result,$i,"OnHand");
$QOO=mysql_result($result,$i,"QOO");
$Description=mysql_result($result,$i,"Desc");
$Cost=mysql_result($result,$i,"Cost");
But with a foreach loop so it isn't as much code.
I was thinking something like this, but it won't execute no matter which way I go about it (parse_str, eval, exec, etc.)
$nDatabaseVars=array("PartNo","Group","OnHand","QOO","Desc","Cost");
foreach ($nDatabaseVars as $X) {
$$X=mysql_result($result,$i,'$X');
}
I need "$$X" to evaluate out so on the first iteration, it changes to $PartNo= and then sets $PartNo to whatever data is in the database on the first line. Which is what this part is: mysql_result($result,$i,"PartNo")
If I echo it out instead:
foreach ($nDatabaseVars as $X) {
echo "$$X=mysql_result($result,$i,'$X')";
}
I can get it to say exactly what I need executed ($PartNo=mysql_result($result,$i,"PartNo");) but not actually get the variable set.
You are passing a string containing "$X" to mysql_result, not the name of your column. Remove the single quotes:
$$X=mysql_result($result, $i, $X);
$$X=mysql_result($result,$i,'$X'); // these single quotes around $X avoid your actual string to be used.
$$X=mysql_result($result,$i,"$X");
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
Is it possible to store PHP syntax in variables for later use and repetition like this:
$ifStart = "if(";
$ifEnd = "){ echo 'Test'; }";
$ifStart 'A' == 'B' $ifEnd;
Edit: What I'm trying to accomplish is this:
I have 3 form fields, and when the PHP script is loaded, any of the three can be set. None can be set, two, one... So I need some way to determine how many are set and what to output according to that. That's why.
Edit: Right, so I have one HTML Select and two text input fields. My script checks if those fields are set (isset) and does some code accordingly, putting information into arrays etc. What I want to do now though, is to check if the variables have been set one by one, so I can output the correct results which I have stored in arrays.
New edit: This is obviously so hard to explain. But imagine a search engine where you decide which fields you'd like to fill out and then the script checks which fields are set and loops through the array with all the results, only gathering out the elements with sub-elements corresponding to the requested search, that's what I'm trying to achieve.
Here's the array design with AGE and COUNTY selected/set in the POST (hence why there's no [city] elements:
Array
(
[1] => Array
(
[id] => 1
[age] => 19
[county] => 4353
)
[2] => Array
(
[id] => 2
[age] => 20
[county] => 4020
)
[3] => Array
(
[id] => 3
[age] => 30
[county] => 4020
)
)
Still trying to figure out how to only select out a specific array element depending on -its- contents. For example, I have an array like this:
Array ( 1: [age][county], 2: [age][county], 3: [age], 4: [county], 5: [age][county] )
I'd then like to only select the IDs containing both age and county, in this example ID 1, 2 and 5.
Edit: It'll be similar to a SQL query: WHERE age AND county, only this is in an array
It is possible...
BUT
if you have to do it, there's definitely something wrong with your design!
[Edit after your edit]
Your edit shows me that I was right. What you're trying to do, can be accomplished in a better way!
So if I understand you correctly, you want to alter your output according to which form fields have been filled/answered by the user. So far you are storing some values from the $_POST array in another array. In order to generate your output, it would be best to loop over that array and concatenate strings, depending on what has been filled.
foreach ($myArray as $formField => $value)
{
//do something for each $formField, depending on the $value
}
If that still leaves you puzzled, comment here.
The way you wrote it, it would not work, you would need to use eval(). The use of eval() , is in most cases bad practice. That would not be the main problem though, the main problem is, that such code is hard to read, hard to debug as well as maintain and hard to document. All it all, it is bad practice and will lead to a bad solution and more problems.
One clean way (clean because it avoids eval()) to do relatively dynamic code would be to store either a function name or, after php 5.3, a function reference.
E.g. something like:
$callback = "truth_check";
$condition_result = ($a == $b);
if(is_callable($callback)){
$callback($condition_result);
}
See a running example here: http://ideone.com/1SBYS
In your case the callback could be a result to run, e.g. "print_message_on_true_input" as some comparison function and the input could be the result of a conditional tested anywhere in your code, e.g. $print = (false || $a == $b);
Give your specific use cases, though, because 90% of the time intended behavior can be acheived much less fragily without resorting to any dynamic code at all.
Is it possible? Yes, using eval.
Should you do it? NO NO NO NO PLEASE DON'T.
No. You can use functions instead.
function my_compare($a, $b, $symbol = '==') {
eval('$result = $a ' . $symbol . ' $b;');
if ($result) echo 'Test';
}
// ...
my_compare('A', 'B');
Keep in mind the comments above that warn you about this idea!
But you could probably do this:
$ifStart = "if(";
$ifEnd = "){ echo 'Test'; }";
eval( " {$ifStart} 'A' == 'B' {$ifEnd} " );
Ok, so what you need has little relation to the dynamic code involved in your original question, so I'm going to start over and propose a different approach entirely:
//INITIALIZE
//get your input variables, defaulting to null
$inputs = array('select'=>#$_REQUEST['select_name'], 'input1'=>#$_REQUEST['input_1_name'], 'input2'=>#$_REQUEST['input_2_name']);
// initialize your output variables
$out1 = $out2 = $out3 = null;
//MANIPULATIONS
//perform actions based on the presence of variables in the array
if($inputs['select'] == 'whatever'){
$out1 = 'select was '.htmlentities($inputs['select']);
}
// .... perform more manipulations, setting output strings ...
// OUTPUT SECTION
echo $out1.$out2.$out3;