I have a string stored in a database that I'm pulling into an array lets say for example the string is "$foo" what I'm trying to do is use that string as a php variable to be interpreted by php, but I can't seem to figure it out. I did try using eval, but I couldn't get that to work in my current code and from what I've read eval() is too dangerous to use in a live environment.
Here is a sample of my code
$result = $sql->query("SELECT * FROM newordersystem");
for ($set = array (); $row = $result->fetch_assoc(); $set[] = $row);
foreach ($set as $item) {
$item[PHPVARIABLE] = stripslashes($_POST[$item[INPUTIDNAME]]);}
The last line is where my problem lies, in that I want "$item[PHPVARIABLE]" to execute as $foo so the result would end up being $foo = 1
Any help or advice would be greatly appreciated!
Strange architecture and I don't get 100% your goal, but if you need:
$item[$item[INPUTIDNAME]] = stripslashes($_POST[$item[INPUTIDNAME]]);}
or
${$item[PHPVARIABLE]} = stripslashes($_POST[$item[INPUTIDNAME]]);}
Related
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!
Hi I'm an experienced PHP developer without any OOP skills and I'm looping round a result and need to concatenate a string like this:
while($row = $DB->fetchArray($homeResult))
{
$labelObject->getcustomerCycle($row['customer_uid'],$_REQUEST['start']);
}
//then output $labelObject.
So with each loop I need:
$labelObject += $labelObject->getcustomerCycle($row['customer_uid'],$_REQUEST['start']);
or something that does the same job :) Thanks!
If I understand correctly you just need to store the results of all the calls. You can do this using a standard variable:
$string = '';
while($row = $DB->fetchArray($homeResult)){
$string .= $labelObject->getcustomerCycle($row['customer_uid'],$_REQUEST['start']);
}
echo $string;
I want to initialize array(in my case it's multidimensional) and I want to retrieve reference to a separate variable so i could access it via that variable.
For example to achieve this im writing two lines
$multidimensional[$some_key] = array();
$item = &$multidimensional[$some_key];
This thing works just fine, but if I wanted to do this in one like I had tried:
$item = &$multidimensional[$some_key] = array(); // syntax error
Question is there a way to do this in single line?
How about:
$item = &($multidimensional[$some_key] = array());
?
i am new to php, and i am trying to do a script that reads an CSV file(file1.csv) and compare the words in the file with words in a html file (file2.html), if word in file2.html match with the key part in file1.csv it should change the file2.html contents with the value of the key matched ..
what i have done so far is this :
$glossArray = array();
$file_handle = fopen("file1.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 10000,';');
$glossArray[$line_of_text[0]] = $line_of_text[1];
$counter++;
}
fclose($file_handle);
$file = file_get_contents("file2.html");
foreach($glossArray as $key => $value){
$results = str_replace($key," means ".$value ,$file);
}
echo $results;
i think that my problem occurs when i try to iterate and change values .. because what i see is only the contents of file2.html unchanged
any help would be appreciated
thank you in advance
Nader
P.s. i edited the old code with the new one after your valuable advise .. now it's like this .. but still doesnt work.
Update: changing the foreach with :
$results = str_replace(array_keys($glossArray), "means ".array_values($glossArray), $file);
solved the problem .. but another one comes up: now every time it replaces a string it adds the word 'Array' ahead of it.
You're passing the entire $glossArray in to str_replace each time. You're also passing the initial file contents in each time you do str_replace, so at most you'd see one replacement. I think you want to change to something like this:
$results = $file;
foreach($glossArray as $index=>$value)
{
$results = str_replace($index,$value ,$results);
}
Since str_replace allows arrays for the first two parameters (as another user mentions) you could also do something like this instead of a loop:
$results = str_replace(array_keys($glossArray), array_values($glossArray), $file);
Yes, the problem is in your second foreach. It should read like this:
foreach($glossArray as $key => $value){
$results = str_replace($key,$value ,$file);
}
You forgot the key, so it's replacing every instance of every value in $glossArray with the $value. Good luck with that!
Why are you opening file2.html for reading and writing, then grabbing the contents of it?
(BTW - this is going to go horribly wrong on a system with strict locking)
foreach($glossArray as $value)
{
$results = str_replace($glossArray,$value ,$file);
I think this should be
foreach($glossArray as $old=>$new)
{
$results = str_replace($old, $new, $file);
Although it would be a lot more efficient to load the pairs from the glossary into 2 seperate numbered arrays, then just call str_replace once.
Your first parameter for str_replace should not be $glossArray as that's an array and not the string to replace.
I assume that your CSV-file contains something like "SEARCH;REPLACE"? In that case, your foreach should look like this: foreach ($glossArray as $searchString => $value).
Then try
$file = str_replace($searchString, $value ,$file);
instead of
$results = str_replace($searchString, $value ,$file);
because right now you're overwriting $results again and again with every str_replace ... echo $file when you're done.
BTW: What's $counter doing?
The solution to your new problem (which should really be it's own question, not an edit of the existing one) is that array_values returns an array, and when you concatenate an array with a string, php inserts 'Array' instead of the value.
$results = str_replace(array_keys($glossArray), "means ".array_values($glossArray), $file);
is incorrect. You should do this instead:
$vals = array_values($glossArray);
foreach($vals as $k=>$v)$vals[$k] = 'means '.$v;
$results = str_replace(array_keys($glossArray), $vals, $file);
Notice that the values of glossArray are extracted, and each value concatenated with your string - if you just try and concatenate the string with the array, you'll get a string, not an aray.
I have data in a MYSQL DB that looks like this:
id,parentid,name,count
1,0,top,10
2,1,middle1,5
3,1,middle2,5
4,3,bottom1,3
5,3,bottom2,2
and want to output it via PHP as a heirarchical JSON string where 'top' has a collection of 'middle's etc.
Get my drift? Anyone have a recursive PHP function to help?
if you've got your data in a PHP array/associative array, then you can use PHP 5.2's JSON functions:
http://www.php.net/manual/en/function.json-encode.php
keep reading on that page to the comments area, they practically give away the code without the fun of figuring it out yourself.
You can use the function here http://tagarga.com/blok/on/061029 to convert your adjacency list to a nested array, then json_encode() it.
function adj_tree(&$tree, $item) {
$i = $item['id'];
$p = $item['parentid'];
$tree[$i] = isset($tree[$i]) ? $item + $tree[$i] : $item;
$tree[$p]['_children'][] = &$tree[$i];
}
$tree = array();
$rs = my_query("SELECT * FROM categories");
while($row = my_fetch($rs))
adj_tree($tree, $row);
echo json_encode($tree[0]);