In an attempt to keep php code seperated from html as much as possible in my pages, I'm trying to create a function which can be used to populate list/drop down boxes on other pages.
Using msqli, I have queried my table "acc_vat_rates! and selected the two fields I am interested in, "vat_rate_id" and "vat_rate_name"
I then loop through the result and populate an array called $vatratearray, code below...
<?php
function vat_rates(){
$conn = new mysqli("192.168.1.81", "root", "", "cloudoneaccountsdb");
$queryvat = "SELECT vat_rate_id,vat_rate_name FROM acc_vat_rates ORDER BY vat_rate_id";
$resultsvat = $conn->query($queryvat);
//SET UP AN ARRAY NOW
$vateratearray = array();
while ($rowvat= $resultsvat->fetch_assoc())
$vatratearray[] = $rowvat['vat_rate_id']." "." ". $rowvat['vat_rate_name'];
//print_r($vateratearray);
foreach($vatratearray as $key => $value)
//echo "<p>{$value} <?br></p>";
echo '<option value="'.$value.'">'.$value.'</option>';
}
?>
This function is stored in a page called "global_functions.php to be included in other pages
All of the above works fine. I then use the function "function vat_rates() as the option value for a list box on an other page, however, this is where my problems begin. When the function populates a listbox it displays the record_id and the name alongside each other, this is ok but when I post the selected line, it also posts the "id" and the "name" which is not what I require. I only want the "id" to be posted for inclusion in the DB.
I've been at this for a fair while, so any help would be appreciated.
Thanks...
David
You could just change your while loop and remove the foreach:
while ($rowvat= $resultsvat->fetch_assoc()){
echo '<option value="'.$rowvat['vat_rate_id'].'">'.$rowvat['vat_rate_name'].'</option>';
}
Try this:
while ($rowvat= $resultsvat->fetch_assoc())
{
array_push($vatratearray,
array('vat_rate_id' => $rowvat['vat_rate_id'],
'vat_rate_name' => $rowvat['vat_rate_name']
));
}
foreach($vatratearray as $key => $value)
{
echo '<option value="'.$value['vat_rate_id'].'">'.$value['vat_rate_id'].' '$value['vat_rate_name'].'</option>';
}
You can improve this code a lot....you can even create the options inside the while loop; just like the other answer XD
Saludos ;)
Related
i want to display data from database and also i have created function in model file which is showing data from database but all values are shown in the array format.
problem is that when i print echo $values['title']; in foreach loop it is showing only first letter from title array??
model code
function reviewcitypage()
{
$cacheKey = 'city_page';
GigaCache::set(array('duration'=>"+1 minutes",'path'=>CACHE));
$cachedCategoryData = GigaCache::read($cacheKey);
if($cachedCategoryData && !cr('DynamicPage.field'))
{
$recentactivity = $cachedCategoryData;
}else
{
$recentactivity= $this->find("list",array("conditions"=>array("status"=>1),'fields'=>array('title','body','rating'),'recursive'=>-1,'limit'=>10));
//dont't set cache if dynamic field
if(!cr('DynamicPage.field'))
{
GigaCache::set(array('duration'=>"+1 minutes",'path'=>CACHE));
GigaCache::write($cacheKey,$recentactivity);
}
}
return $recentactivity;
}
view file
$ReviewObj = cri('Review');
$recentactivity = $ReviewObj->reviewcitypage();
foreach ($recentactivity as $name => $value){
foreach($value as $values)
{
echo $values['title'];
}
}
**problem is solved now thanks for support **
i have changed the code in model file and it is woking now
$recentactivity= $this-
>find("all",array("conditions"=>array("status"=>1),'recursive'=>-1,
'limit'=>10));
Your find() query is preparing the data as a 'list'. in cake lists are always key => value pair arrays. so in your view when you use the second foreach loop you are saying foreach character in a string...do.....
in your example $value can only be a string. foreaching it can only make $values a single char.
Let me know if you still unsure what i mean. not the best at explaining what i mean
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-list
Because you are after 3 fields I suggest using either first or all in place of list as the first argument in the find() method.
I'm very new with PHP/Mysql, but I'm trying to make movie database.
There's a form where people can put in info about the movies, and the send button stores it in my database. Then another web page displays the movie list.
The text input and dropdown selections were easy. What I'm really struggling with is the multiple checkbox part. After hours of struggling I finally learned about the php array and how I can store all the values from my checkboxes using implode. My code looks like this:
$genre = implode( ';' , $_POST['genre'] );
This saves all the selected genres in the database, seperated by ;
However, I need help in displaying this data on my html page the way I want:
First off, I want to retrieve the results in a html list, instead of a;b;c
Second, I want to change a;b;c etc to actual words - for example Horror, Action, Comedy. Can this be done?
Hope someone can help! Thanks!
EDIT:
A friend told me that the best way to handle multiple checkbox values is to store them in a different table (moviegenres) and use mapping. So I rearranged my database like this:
One table called 'movies' that has the columns 'movieID' and 'title', and one table called 'moviegenres' that has the columns 'movieID' and 'moviegenre'.
I can still save the title into 'title' in 'movies', but when I want to add a command for adding genre to the 'moviegenres' table, nothing works...
What is the simplest way to do this?
Do I need to different commands for inserting into two tables, or can I do everything in one command, using one variable?
You can take the data say
$genre = 'a:b:c';
and use
$genreArr = explode(';', $genre);
to get this as an array. where you can get the values like
$genreArr[0] = 'a';
$genreArr[1] = 'b';
then in php page, use this code:
echo '<ul>';
foreach($genreArr as $g)
{
echo '<li>'. $g.'</li>';
}
echo '</ul>';
Yes you can used the explode() function to get an array of database checkbox values like you have fetching from db a;b;c
$values = explode(';', $dbcheckboxes);
After this just display in html. If you want to display actual words then make one array of actual words like
$actual_words = array(a => 'Horror', b => 'Action', c => 'Comedy');
Just compare the above database values with actual words array keys and you will get it.
You can get data explode it and loop it to print those values in html.
$checkbox_values=explode(";","a;b;c");
$map=array("a"=>"Apple","b"=>"banana","c"=>"carrot");
foreach($checkbox_values as $value)
{
echo "<p>"+$map[$value]+"</p>";
}
This would be a solution for your question.But since creating a map variable wont be dynamic, it is better to store the display string as it is to database such as "apple;banana;carrot".
$genre = implode( ';' , $_POST['genre'] );
$array_values = explode(';', $genre);
foreach ($array_values as $values) {
echo $values.'<br>';
}
My page grabs some records from a mssql DB, reads them into an array called $rows, with 3 columns:
ComputerName, Room, time_in_days
From $rows a second array is created (called $graph) with two columns, with the key being time_in_days from $rows, and the value column being a count of how often time_in_days occurred in the first array. The $graph array is used to create a number of HTML divs to give the impression of a graph.
I then want to be able to click on each individual div and using the $key value from the $graphs array, want to look up the rest of the information associated with all records in $rows where $graph[$key] matches $rows['time_in_days'] and display those records on the page.
But I have got stuck! I don't know where to put the function, the if statement(see code below) and at the moment, it doesn't even seem to be running the function. I don't even think I have the function code right. So if you could help with any of that I will very much appreciate it!
This is the code where the divs/graph is created:
foreach($graph as $key => $value){
$width = $value * $factor;
$page .= '<div style="width:40px;display:inline-block;">'.$key.'</div><div class="bar '.$key.'" style="width:'.$width.'px;"></div><div style="display:inline-block;margin-left:2px;">'.$value.'</div><br/>';
}
This is the function so far:
function SearchDays($key, $page, $rows) {
$computers = array();
foreach ($rows as $arr){
if ($key == $arr["time_in_days"]){
$computerName = $arr["ComputerName"];
$computers[$computerName] = $arr;
}
}
$page .= '<p>computers array from function SearchDays(): <pre>'.print_r($computers,true).'</pre></p>';
return;
}
And this is the if statement that makes the if statement that should run the function:
if (isset($_GET['barclick'])){
SearchDays($key, $page, $rows);
}
$page is just a variable that holds everything that is printed out onto the HTML page. The page itself can be seen here: cems.uwe.ac.uk/~s3-gupta/histogram/index.php. The whole page code can be got here: https://www.dropbox.com/s/h2q7x9xxtjbktx9/index.php
Thanks in advance. Please let me know if you need me to clarify things. I try and be as clear as possible on here, but usually don't manage it, so let me know if you need more.
I have a form that allows a user to add and delete objects from an array. The deleting process works by taking the array and dumping all the contents into a dropdown list the user can select what they want to delete from.
<?php
session_start(1);
if (isset($_SESSION['array'])){
$narray = $_SESSION['array'];
if ($narray != NULL){
echo "DDDD";
}
echo 'Select an object to delete: ';
echo '<select name=deleteob>';
foreach($narray as $drop){
echo'<option value="'.$drop.'">'.$drop.'</option>';
}
echo '</select>';
Whenever all of the contents are deleted, the array does not 'clear'? I'm not sure the word, it does not seem to be actually emptying. The echo 'DDDD' is to see if the array has something contained inside of it. I've also tried seeing if the array is NULL, but neither will echo anything, but the dropdown list is still being created with an empty selection. The array is being pulled from a process page by a session variable on another page. Basically array has nothing inside of it but acts like it does. Anything i am doing wrong to cause this? Sorry for bad english
Change
if ($narray != NULL) {
to:
if (!empty($narray)) {
If you delete all the elements of an array, it's still an array, and is not equal to null.
I need some help please. I need to create a drop down list and then when the option is submitted a php script must run. The complication is I can't hard code any of the values. I need it to be 'dynamically created'
config.php
$number_Of_Option="3"
$Option_One_Name="Cars"
$Option_One_Year="2000"
$Option_One_Colour="Blue"
$Option_Two_Name="Houses"
$Option_Two_Year="2003"
$Option_Two_Colour="Pink"
$Option_Three_Name="Bikes"
$Option_Three_Year="1990"
$Option_Three_Colour="Orange"
Now I need the drop down to be made with the name in the drop down to be "Cars", "Houses", "Bikes" but they must be variable based so if I change "Cars" it will change.
Then when the option is submitted (Option Two in this case) I need $Option_Two_Year and $Option_Two_Colour to be passed to a script where these two variables are the variables in the script. So the script is always the same however if drop down one is selected then it uses variables 1 if 2 then it uses variables 2 etc. I also need to it work for an infinite number of options so at any time I can got into the config.php and add another option with its own variables. It can use arrays and jquery if that's easier or necessary.
Thanks
Make an external file, eg. options.php, with this code:
$options = array();
$options["cars"] = array("2000","blue");
$options["houses"] = array("2003","pink");
$options["bikes"] = array("1990","orange");
Include this file in both the form page, and the parse script, using include("options.php");
In the form page, do:
include("options.php");
echo '<select name="option">';
foreach($options as $name => $values)
{ echo '<option value="' .$name .'">' .$name .'</option>';
}
echo '</select>';
In the parse script, do:
include("options.php");
$chosenValue = $_POST['option'];
list($year,$colour) = $options[$chosenValue];
Now $year and $colour will contain the year and colour for the option with the chosen name.
You know they invented arrays for this? If you got a reasonably recent version of PHP (I think 1.0 or higher ;) ), you could store this data like:
$options = array(
'Cars' => array('Year'=>'2000', 'Colour'=>'Blue'),
'Houses' => array('Year'=>'2003', 'Colour'=>'Pink'),
'Bikes' => array('Year'=>'1990', 'Colour'=>'Orange'));
Then you could get the selected option, and find the matching values by that option:
$option = $_GET['option'];
if (array_key_exists($option, $options))
{
$selectedYear = $options[$option]['Year'];
$selectedColour = $options[$option]['Colour'];
// Process them.
}
If you don't want to (or are not allowed to) use arrays, you'll need to match every variable:
if ($option === $Option_One_Name)
{
$selectedYear = $Option_One_Year;
$selectedColour = $Option_One_Colour;
}
elseif ($option === $Option_Two_Name)
{
...
Of course, you can speed this up a little bit. You can make an array of numbers and get the matching variables by their names
$numbers = array('One', 'Two', 'Three');
foreach($numbers as $number)
{
$optionVar = 'Option_' . $number . '_Name';
if ($option === $$optionVar)
{
$yearVar = 'Option_' . $number . '_Year';
$selectedYear = $$yearVar;
...
}
}
That code is more complex, but it won't need to be expanded if you get more option. You only need to update the Numbers array.
But still, as you can see, it will be easier to use arrays.