I've got the below PHP which works great when the array of locations only have 1 value, but when it has any number more than 1, the information on the first location keeps printing out blank. The array is set by calling explode on a comma-delimited list. When I set the array manually immediately before the loop, it works great! Yet not when I use explode, even though I printed the array and can confirm it's getting set up just as I expect (with the correct 0 index). The code I have is:
echo "<ul>";
foreach ($locations as &$value)
{
$locationDetails = mysql_query("SELECT id, name FROM locations WHERE id='$value'");
$locationDetailRow = mysql_fetch_assoc($locationDetails);
echo "<li>".$locationDetailRow['name']."</li>";
}
unset($value);
echo "</ul>";
I've confirmed that the query does not fail, that $value is what I expect it to be, and that the name does exist for the first $value in every case.
Any reason this should be failing on the first case when there are multiple locations?
Related
Please understand this is not how I would have designed this, nor is it the proper way to do something like this.
However, since I was given this task, and have absolutely no way around the way the data is structured, I am tasked with working with what I was given.
I have a table structured as such:
ID
UniqueName
DisplayName
Tag1
Tag...
Tag27
Yes, I have 27 columns, Tag1 - Tag27
NOTE: This cannot be changed due to the data coming from 15 year old software that is not updated, nor is there any chance of it being updated. (Hence my dilema)
I am getting my resultset utilizing PDO's fetchAll(PDO::FETCH_ASSOC)
How can I loop over these Tag* columns, and just the Tag* columns, without having to type out rs[$i]['Tag#'] for each individual one, also noting that there may be instances where I could have 14 Tag columns` instead of the 27 I state in this example...
COLUMN CODE:
// prod_opts_value_fields_prefix = "Tag"
foreach ($rs[$i] as $key => $val) {
if ( strpos ( strtolower ( $key ), strtolower ( $prod_opts_value_fields_prefix ) ) !== false ) {
$vals .= $val . '|';
echo $val . '<br />';
}
}
Nothing is getting echo'd
You could run a foreach over the rs[$i] and check if the key contains 'Tag' with strpos and go from there.
Alternatively you could use just a for loop running on 1 to 27 (or any maximum Tag value) and have an if condition checking if rs[$i]['Tag$N'] (where N is the for loop counting variable) isset, if not break from the loop as that means you've gone through all possible Tags.
The second solution here does have the assumption Tags are always numbered sequentially and in ascending order.
If you need it in multiple places, I'd probably add a setting to a preferences array or a constant that you can easily re-use:
const TAG_COLUMNS = [
'Tag1',
...
'Tag27',
];
You can use that wherever you need it to loop over a result set.
I have this array in php code. I want to have that whenever page is being called it should print value of first array index and when next time second value of array index and so on... what modification I could do? for now it´s printing everything when being called single time.
<html>
<?php
$addresses = array('ifcbxespra', 'ifcheqjbmea', 'ifcqiknsa', 'ifcqirtjla', 'ifcwqsrlmn', 'ifclmkmzhz','ifcwdujhgc','ifcihddngh','icffhzudcd','ifchnsqzgs','ifcgssqrhg');
foreach ($addresses as &$value) {
echo $value ;
}
?>
</html>
I'm not sure if I understood what you want. But if you want to print the first array's value when the page loads one time, the second array's value when the page loads another time and so on, you can do this:
<?php
if(!isset($addresses) || empty($addresses)){ //checks if the array is not initialized or if it's empty
$addresses = array('ifcbxespra', 'ifcheqjbmea', 'ifcqiknsa', 'ifcqirtjla', 'ifcwqsrlmn', 'ifclmkmzhz','ifcwdujhgc','ifcihddngh','icffhzudcd','ifchnsqzgs','ifcgssqrhg');
echo $addresses[0]; //print the first value
array_splice($addresses, 0, 1); //removes the first element of the array and reindexes it
}else{
echo $addresses[0]; //print the first value
array_splice($addresses, 0, 1); //removes the first element of the array and reindexes it
}
The logic behinds it is: if the array already exists and is not empty (it has values), print the first value and then remove it, so next time the first value will be the second actual value. When the array is empty, redefine it as to start again.
You can search for more information on array_splice() here.
P.S.: you have to use PHP's $_SESSION to save the array between the pages.
You can use something like $_SESSION and store there the last index.
For example:
$array = array('one', 'two', 'three');
if (!$_SESSION['nextIndex'] || $_SESSION['nextIndex'] >= count($array)) {
$_SESSION['nextIndex'] = 0
}
// print the value
echo $array[$_SESSION['nextIndex']];
// increment the nextIndex
$_SESSION['nextIndex']++;
NOTE: This will only work for the same user. Each page reload will increment the array index. But if you need some cross-user counting, then you have to store the information somewhere on the server, like a DB or even a simple txt file.
Check out this example: http://hibbard.eu/how-to-make-a-simple-visitor-counter-using-php/
Finally I solved this problem with the MySQL. created a column with all code. and then call the script every-time when user press button. In the script first I fetch first raw and print that value, and then, delete that raw. so every-time user will get unique value from the list of code And it is working fine.
i've a array problem couldn't just solve it:
here's the code that is already in a foreach loop. i'm getting the $row->class_id value from this loop. it works fine and get me the total students row within an array and i preserved it in $total_student_of_this_class variable. i used another foreach loop for storing the result of first loop and then second loop and so on. but this loop gives only first loop result.
i need to combine the all array of total iteration of the loop.
$total_student_of_this_class =
$this->db->select('student_id')->where('class_id',
$row->class_id)->get('student')->result_array();
echo count($total_student_of_this_class);
// prints 2 in the first row of the output table and 5 in the second
row for me.
$total_student = array();
foreach ($total_student_of_this_class as $tt)
{
$total_student[] = $tt;
}
echo '<pre>';
print_r($total_student_of_this_class);
echo '</pre>'
echo count($total_student);
// prints only 2 outside the loop (not 7)
pls someone help me.
The problem here is seems to be with $total_student = array();: initializing array inside an other loop it always starts it from zero values array, so you get only results from one iteration inside it and doesn't collect all datas.
You can also look at array_merge php function.
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");
Hello I was wondering how to do the following as I have been going around without an answer. So I will try to simplify as much as I can.
I have set some values for an associative array
$vNArray ['Brandon'] = $item[3];
$vNArray['Smith']= $item[4];
$vNArray ['Johnson']= $item[5];
$vNArray ['Murphy']= $item[6];
$vNArray ['Lepsky']= $item[7];
foreach ($vNArray as $key => $value){
if(!empty($value)){
$result .= "\t\t\t\t<li><strong>$key</strong>" .$value. "</li>\n";
}
But now I want to target specific values within that array so here is another array:
$display_id=array('Brandon', 'Murphy');
foreach ($vNArray as $key => $value){
if(!empty($value)){
//Looks into the display_id array and renders it differently
if (in_array($key, $display_id)) {
$data .= "\t\t<li id=\"".$vNArray['Brandon']."\">".$vNArray['Murphy']."</li>\n";
} else {
$result .= "\t\t\t\t<li><strong>$key</strong>$value</li>\n";
}
}
The result for the first condition is correct but repeated for both in_array values:
<li id="Brandon Value">Murphy Value</li>
<li id="Brandon Value">Murphy Value</li>
Below is correct:
<li><strong>Smith</strong> Value of Smith</li>
<li><strong>Smith</strong> Value of Johnson</li>
<li><strong>Lepsky</strong> Value of Lepsky</li>
How do I stop it from repeating depending on the number of arrays?
$data .= "\t\t<li id=\"".$vNArray['Brandon']."\">".$vNArray['Murphy']."</li>\n";
You've hardcoded the vNArray keys, so that regardless of which name got matched, you're always outputting the same values. You'd want
$data .= "\t\t<li id=\"{$key}\">{$value}</li>\n";
instead.
There's no need to do the string concatenation as you are. PHP can insert array elements into a string nicely, and it eliminates the need to escape quotes everywhere, which means for hideously ugly code to read through.
Look at your loop carefully.
You're using a foreach loop, which means you are going through the array each time.
Your if(in_array(...)) condition checks to see whether the key is in your $display_id array. That happens twice, for Brandon and Murphy.
When that condition happens twice, $data is appended twice meaning you will get the results displayed twice.
I'm not sure what this helps, but just look at your loops carefully. Can you clarify what you're exactly trying to achieve, or what your desired output is?
Good luck.
EDIT:
I reread your question and realized something -- do you just want your output to print once?
Look into the break syntax. After you append it in the if condition, add a break; and that will break out of the loop printing it once.