Make HTML list from PHP array? - php

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>';
}

Related

Using a foreach statement to populate a dropdown list - it display as a single string

When populating a dropdown list using a foreach statement on array, it display a single item as a string. however, it can populate the list correctly using this syntax ["test1","test2"]
foreach($dataNew[$i]['message'] as $x => $item){
$myMessage[]='"'.$item['Lots'].'"';
}
$lots=[implode (',', $myMessage)];//does not work
//$lots=['4342355555555#1', '32335455#5'];//works fine
$dataNew[$i]=['Lots'=>[$lots]];
Any ideas?
Here is an example of corrext concatination, assuming some details of your problem, which are not quite clear by now.
Assuming: the $dataNew parameter holds an array of strings at [$i]['message'] which contains lots, which are seperated by commas, and come from some statistical process.
The output shall be an two-dimensional array, which merges all lots of one iteration into one list. So the reslut is a list of lists of lots (foreach $i).
$currentLotsList = $dataNew[$i]['message'];
//iterating over the lots of the current sample - which are a chain of strings seperated by commas
foreach($currentLotsList as $csvLots){
//getting the lots into an array
$currentLotsArray = explode(",", $csvLots);
//adding this list to the major list of $i,
if(!isset($dataNew[$i]['Lots']) ){
//createing the array if not set now.
$dataNew[$i]['Lots'] = [];
}
$dataNew[$i]['Lots'] = array_merge($dataNew[$i]['Lots'], $currentLotsArray);
}

How to display data without redundancy

i want to display in my system just one record with the same id.
for example: 01,01,02,02,03,03.
I just want to display 01,02,03.
The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed.
$number = "01,01,02,02,03,03";
$result = implode(',',array_unique(explode(',', $number )));
echo $result; // output 01,02,03
Happy Programming

Getting multiple value from single cookie using php

I want to implement shopping cart in php. I am using single cookie to store multiple product id and quantity. Now i want to fetch these values from the cookies.
The data is stored in this format : {Product_id-Quantity}
Like this :
A-2,B-4,C-1,D-3
Now i want to use explode function to get these two values product id and quantity separately.
I do not know how to do this. Can anyone figure out a way to implement this ?
here you go - this saves your cookie-string in a PHP array:
$str = "A-2,B-4,C-1,D-3";
$arr = explode(",", $str);
foreach($arr AS $row)
{
$piece = explode("-", $row);
$cookie[$piece[0]] = $piece[1];
}
var_dump($cookie);
notice: your names and values must not contain , or - because you use them as separators.

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

Create a blank record via PHP based on MySQL table

I've got a home-grown LAMP app that uses the same HTML code for the "Modify record" and "New record" pages based on whether it is passed a blank record or a non-blank record. Currently, I'm creating the blank record by selecting a single record from the MySQL table and manually setting each field (by name) to NULL. There's got to be a better way to do this, but the search terms to find what I need are just too darn generic. I've looked at using something like mysql_fetch_array or get_class_vars, but I just can't get them to work. Here's what I'm trying to replace with something a bit less manual:
// Select a row, any row... (using CodeIgniter)
$q = $this->db->get($this->config->item('db'),1);
// For each ... um ... one ... row, add it to $data
foreach ($q->result() as $row) {
$data[] = $row;
}
// set each **KNOWN** field to NULL
$data[0]->column1 = NULL;
$data[0]->column2 = NULL;
...
I know it's a dirty hack, but it works. What's the "right" way to do this?
I believe you are doing exactly this:
$data[0] = (object) array_fill_keys($this->db->list_fields('your_table_name'), null);
Reference: CI->db->list_fields(), array_fill_keys(), type casting
If you're getting 1 row only, you'd better off using ->row() method instead of a resuls() & useless foreach loop
e.g:
$row = $this->db->select('*')->from('table')->get()->row();
getting to your problem now, you'll have to define the fields you're using something like this
$fields = array('id', 'name', '...etc');
then you'll do something like this to get empty if not available
foreach ( $fields as $f ) $data[$f] = isset($row->$f) ? $row->$f : NULL;
this will make all fields available in your $data, so you can pass it to a view.

Categories