Php - Find only one number in a string - php

I have a php script that loads different IDs and send them to a page on a GET variable, they are all separated by a coma:
.../page.php?items=12,13,43,17,
I then load a mysql with a while loop so that a table shows up, and I need to see if the id of the table item is the same then it adds a style to that table row.
So what I did was:
$style = (strstr($_GET['ids'], $segn['itemid'])) ? 'style="background:lightgreen;"' : '' ;
<tr class="gradeX" <?= $style ?> >;
In this case it worked for single numbers. But in case i have this IDS: 1, 2, 3 ... 12 and the page get request is "page.php?items=12" I get the ids '12', '1' and '2'.
I thought i could use explode(',' , $_GET['ids']) but then I guess it goes too long.
How do I get those the ids? (I've no affinity whatsoever for regexp...).

You have to work with the ids as an array, not as a string. So make an array first:
$ids = explode(',', $_GET['items']);
And then check if the current item is in the array:
$style = in_array($segn['itemid'], $ids) ? 'style="background:lightgreen;"' : '';
That said, you should be using a CSS class instead of inline styles.

Instead of:
strstr($_GET['ids'], $segn['itemid'])
You could do this:
in_array($segn['itemid'], explode(',',$_GET['ids']));

You don't need regex for this.
Split your get variable using explodes as you did:
$items = explode(",", $_GET['items']);
Be careful- you used the wrong name in your code (your get variable is "items", not "ids");
and then use in_array to check to see if it's in there.
$style = in_array($segn['itemid'], $items) ? 'style="background:lightgreen;"' : '';

Related

How do I store the result of sql without column name in php variable?

I’m trying to sore the result of sql in a variable. following is the sql(eloquent) :
$key = $request->input('product_key'); // from previous page
$category_id = ProductModel::select(‘category_id’)->where(‘product_id’, $key)->get();
echo $category_id;
but when i echo it , the output looks like [{“category_id”:301}]
i want only 301 to gets save in variable so that i can use it further ??
Basically i want to get all the products who's category_id is same as that of a given product. Note i have only prodcut_id.
Maybe you are refering to the value method. Find more about it here
https://laravel.com/docs/5.2/queries#retrieving-results
If you don't even need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly:
example usage from the docs
$email = DB::table('users')->where('name', 'John')->value('email');
Try using Eloquent's pluck method: https://laravel.com/docs/5.2/collections#method-pluck
$key = $request->input('product_key');
$category_id = ProductModel::where('product_id', $key)->pluck('category_id')->all();
echo $category_id;
This should result in an array with a single element, which is the category_id you search for (or more elements in case key matches more than one row, but only values as you want).

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.

Make HTML list from PHP array?

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

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