More elegant way of dealing with query string variables - php

The site I am building is a configurator that lets you choose the color of certain items. It will have functionality to share your color config. What it will do is generate a URL with a query string, like ?plate=red&cup=blue&napkin=white My code reads the query string and changes the <img> src value. For example...
<?php
//This stuff is just grabbing the query string values...
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$querystring = parse_url($url);
parse_str($querystring['query'], $color);
$availableColors = array("red","blue","white");
?>
This is my HTML where I'm using PHP to put in the query string color values. This code is also checking to make sure the color is in an array of the available colors.
<div data-color="<?php if( in_array($color['plate'],$availableColors) ) {echo $color['plate'];} ?>">
<img src="img/tablesetting/<?php if( in_array($color['dinnerPlate'],$availableColors) ) {echo $color['plate']."_plate.png";} else {echo "dummy.gif";} ?>">
</div>
<div data-color="<?php if( in_array($color['napkin'],$availableColors) ) {echo $color['napkin'];} ?>">
<img src="img/tablesetting/<?php if( in_array($color['napkin'],$availableColors) ) {echo $color['napkin']."_napkin.png";} else {echo "dummy.gif";} ?>">
</div>
<div data-color="<?php if( in_array($color['cup'],$availableColors) ) {echo $color['cup'];} ?>">
<img src="img/tablesetting/<?php if( in_array($color['cup'],$availableColors) ) {echo $color['cup']."_cup.png";} else {echo "dummy.gif";} ?>">
</div>
What I'd like to do is avoid having a conditional statement every time I want to check if the color value is in my array availableColors. I guess just a more concise/elegant way of doing this is what I'm looking for.

function getColorData($color, $type) {
$result = array('color_name' => '', 'color_img' = 'dummy.gif');
$available_colors = array('red', 'blue', 'green');
if (in_array($color, $available_colors))
$result = array('color_name' => $color, 'color_img' = $color . '_' . $type . '.png');
return $result
}
Usage example:
$plate_color_data = getColorData($color['plate'], 'plate');
echo '<pre>',print_r($plate_color_data),'/<pre>'; // just for test)
<div data-color="<?=$plate_color_data['color_name']?>">
<img src="img/tablesetting/<?=$plate_color_data['color_img']?>">
</div>

First off, is there a reason you are using parse_url....can't just just grab the variables via $_GET or $_REQUEST?
Secondly, if you want to validate your data in_array is a good approach. A simple thing to clean things up is to simply move it all to your php area and then simply output the post-validated data to the html.
If I were building this I would run all this stuff from a database so you would query to database if a color was valid.
I would also consider generating the graphics server side via imagick or gd.

Related

How to change which variable is used, depending on another value

I'm trying to make a fun side project and have come to a stop on a small problem. I am trying to have the echo command placed inside of the while and mysqli_fetch_assoc command as the data changes everytime the page refreshes, from the select from table random function.
I select random items like this:
$survivor_set = random_survivor();
$item_set = random_item();
$firstaidkitaddon_set = random_firstaidkitaddon();
$flashlightaddon_set = random_flashlightaddon();
$keyaddon_set = random_keyaddon();
$mapaddon_set = random_mapaddon();
$toolboxaddon_set = random_toolboxaddon();
$survivoroffering_set = random_survivoroffering();
The problem line of code looks like this:
<?php while($toolboxaddon = mysqli_fetch_assoc($toolboxaddon_set)) { ?>
However I need the words after $ to be changed so was looking for something like this to work:
<?php while($ echo h($item['item']);addon = mysqli_fetch_assoc($ echo h($item['type']);addon_set)) { ?>
This is probably explained poorly, I would appreciate if anyone could lend some time to help me where I can show in more details what exactly I am trying to accomplish.
The code shows the random item that was selected from the table.
<?php while($item = mysqli_fetch_assoc($item_set)) { ?>
<?php echo h($item['name']);?> E.g. Engineers Toolbox
<?php echo h($item['rarity']);?> E.g. veryrare
<?php echo h($item['type']);?> E.g. toolbox
<?php echo h($item['media']);?> E.g. engineerstoolbox.png
<?php } ?>
I am then trying to find a way to put the echo h($item['type']) into the next output. so it would look like this when it is a toolbox.
<?php while($toolbox = mysqli_fetch_assoc($toolbox_set)) { ?>
But then could change due to it being a different item type that was pulled:
<?php while($flashlight = mysqli_fetch_assoc($flashlight_set)) { ?>
Full code, for context: https://zerobin.net/?9f772676aa87df3f#Gxy43WGqShTkL/VG42+t3nT4+sxGhxFy+GDB0B3+YH0=
You should store all your different add-on results in an associative array where the keys match the possible "type" values from your main item query. This allows you to select an item from the array using a string to reference its key - and you can take that string value from your $item['type'] variable.
e.g.
$survivor_set = random_survivor();
$item_set = random_item();
$addons = array(
"firstaid" => random_firstaidkitaddon(),
"flashlight" => = random_flashlightaddon(),
"key" = random_keyaddon(),
"map" = random_mapaddon(),
"toolbox" => random_toolboxaddon()
);
$survivoroffering_set = random_survivoroffering();
Then later on you can select the right set of results from the associative array by selecting the index which matches $item['type']:
<div class="itemaddonscontainer">
<div class="<?php echo h($item['type']);?>">
<?php while($addon = mysqli_fetch_assoc($addons[$item['type']])) { ?>
<img class="<?php echo h($addon['rarity']);?> survivor-item" src="imgs/survivor/itemaddon/<?php echo h($addon['media']);?>"/>
<?php } ?>
</div>
</div>
N.B. mysqli_free_result probably isn't necessary here.

Change icons depending a php condition

I assign a color value to each category of elements. I retrieve the color that has that category and I use it as background-color in a <span> in the following way:
<span class="cat-icon" style="background-color: <?php echo esc_attr( $first_ctg->get_color() ) ?>;">
What I need to do is that depending on the value of that color, I must show one image source or another inside the <span>.
if ($first_ctg->get_color() == red)
show img_01
elseif ($first_ctg->get_color() == blue)
show img_02
endif;
How can I do this properly in PHP?
There are more ways you could do this, I assume you have just two pictures (you can use elseifs otherwise). Solution:
<span class="cat-icon" style="background-color: <?php echo esc_attr( $first_ctg->get_color() ) ?>;">
<?php
$src = "img_02";
if ($first_ctg->get_color() == "red") {
$src = "img_01";
}
?>
<img src="<?php echo $src ?>">
I am finding out the image source in conditions first and then assigning its value to variable $img. Then I am echoing source to src inside php tags.
You can do this with PHP by checking the value of $first_ctg->get_color() and echoing the entire <span> element based on that value, i.e.
switch ( $first_ctg->get_color() ) {
case 'red': // or whatever value you would expect to receive from your get_color() function
echo '<span class="cat-icon" style="background-color:#ACOLOR"><img src="PATH/TO/WHATEVER/IMAGE"><span>';
break;
case 'another color':
echo '<span class="cat-icon" style="background-color:#ANOTHERCOLOR"><img src="PATH/TO/ANOTHER/IMAGE"><span>';
break;
...
default:
echo '<span class="cat-icon" style="background-color:#ANOTHERCOLOR"><img src="PATH/TO/ANOTHER/IMAGE"><span>';
break;
}
It's worth stating that this is arguably a case for using Javascript (or JQuery) to manipulate the DOM based on other elements or attributes, but since your question specifically asked how to do this in PHP that's the answer I gave.
Its Very Simple you need to put some conditions like
if ($first_ctg->get_color() == red)
{
$src = "https://www.example.com/img/background.png";
}
elseif ($first_ctg->get_color() == blue)
{
$src = "https://www.example.com/img/background-2.png";
}
And Into img tag you need to put this variable (i.e: $src)
<img src="<?php echo $src;?>" title="">
Since a category already knows its color. Why not make the icon also a property of the category class ? Then in your vieuw you could simply write something like
<img src="<?php echo $first_ctg->get_icon()">

Display whole fields from group (file + ACF)

I made the ACF plugin group with files to download. In group I have fields "File 1", "File 2"...etc.
I would like to display all attached files to page. It is possible to display all fields belong to group? I try with basic code, but in this case I have only 1 file.
How can I add iteration to this or display all fields?
<?php
$file = get_field('attachment_1');
if( $file ):
// vars
$url = $file['url'];
$title = $file['title'];
$caption = $file['caption'];
if( $caption ): ?>
<div class="wp-caption">
<?php endif; ?>
<ul>
<li><a href="<?php echo $url; ?>" title="<?php echo $title; ?>">
<span><?php echo $title; ?></span>
</a>
</li>
<ul>
<?php if( $caption ): ?>
<p class="wp-caption-text"><?php echo $caption; ?></p>
</div>
<?php endif; ?>
<?php endif; ?>
As all your fields are set up individually, it isn't just a matter of looping through an array of all your fields of the same type (i.e. just your file fields).
There are a few ways that might work for you:
Option 1.
If all the field names for your files follow the same naming pattern and are named sequentially, you could loop using the name.
Example, assuming your fields are named attachment_1 up to attachment_5:
$statement = get_field('name_of_your_statement_field');
//do whatever you need to with $statement
for ($i=1; $i<=5; $i++){
//use the number from the loop to find the file by name
$file = get_field('attachment_'.$i);
if( $file ){
// display file details as appropriate
}
}
Option 2.
If the file field names do not follow the same pattern, you could loop through an array of the field names.
Example:
$statement = get_field('name_of_your_statement_field');
//do whatever you need to with $statement
// Create an array with the field names of all your files
// N.B. This also lets you specify the order to process them
$file_fieldnames = array('file_1', 'file2', 'another_file');
foreach ($file_fieldnames as $fieldname) {
$file = get_field($fieldname);
if( $file ){
// display file details as appropriate
}
}
Option 3. If you want to loop through ALL fields on the post/page, you can save the fields into an array.
This might seem like the most generic approach at first, but it is complicated by the fact that you don't know what type each field is in order to know how to process and display them... you first have to work out what field type it is. You could do this by name (similar to above) or you could try to identify what each field by checking the field content.
Note, checking the field content is very risky, as there are other field types that can have similar featured (e.g. a file is not the only type that can have a url) so I wouldn't advise that strategy unless you are 100% sure you'll never change the field group or add another field group to the post/page.
Example:
$fields = get_fields();
foreach ($fields as $fieldname => $content) {
if (is_string ($content)){
// display the string
}
else if (is_array($content) && $content['url']) {
// then you could assume its a file and display as appropriate
}
}
Note that none of this code is tested. However it should give you an idea of the logic behind each option so you can decide what works for you.
UPDATE based on new code provided:
See below based on the code in your JSFiddle. I've ignored the caption outside the file list because it makes no sense - every file can have its own caption.
<?php
for ($i=1; $i<=5; $i++){
//use the number from the loop to find the file by name
$file = get_field('attachment_'.$i);
if( $file ){
$url = $file['url'];
$title = $file['title'];
$caption = $file['caption'];
// now display this file INSIDE the loop so that each one gets displayed:
?>
<li>
<a href="<?php echo $url; ?>" title="<?php echo $title; ?>" target="_blank">
<span><?php echo $title; ?></span>
</a>
<?php if( $caption ): ?>
<p class="wp-caption-text"><?php echo $caption; ?></p>
<?php endif; ?>
</li>
<?php
} // end if
} // end for loop
?>
<ul>
If you understand arrays, I'd suggest you add the file details into an array and then do a second loop to display the files... however I'm guessing you're not that proficient with basic coding constructs as you don't understand loops, so I've tried to keep it simple. I strongly recommend that you do some tutorials on programming basics if you are attempting to write code.

Using Meta Box Plugin to assign URL to a variable

I'm a little lost here, hoping that someone can help. I'm using the Meta Box plugin for WordPress, and I'm trying to create a process for the user to select an option from a predefined list, and then assign a URL to that option as a link. Im trying to define the URL in a variable, and then call it in a function, but I'm still a little green on PHP syntax. this is my code now:
<?php
$article_url= rwmb_meta('orion_2016_article_url', 'type=URL');
if (rwmb_meta('orion_2016_article_source') != '') {
echo '<a href= ("$article_url") target=blank>';
echo rwmb_meta('orion_2016_article_source');
echo '</a>';} ?> on <?php the_date(); ?>
Since the options are already predefined, it seems like assigning a random URL to one of the options should be pretty simple. Hopefully this makes sense!
You need to to place variables you wish to echo inside double quotes or simply concatenate strings using . as in my example. Note that I didn't check the plugin's specific syntax, only general PHP syntax.
<?php
$article_url= rwmb_meta( 'orion_2016_article_url', 'type=URL' );
if (rwmb_meta('orion_2016_article_source') != '') {
echo '' . rwmb_meta( 'orion_2016_article_source' ); . '';
} ?> on <?php the_date(); ?>

Remove old parameter in URL (PHP)

I'm using PHP to create a pagination for a table.
I'm using the following code to create the pagination link
<a class='page-numbers' href='$href&pagenum=$i'>$i</a>
With $href
$href = $_SERVER['REQUEST_URI'];
It works well, however, it messes with the address bar, adding each time a new pagenum parameter.
So it becomes pagenum=1&pagenum=3&pagenum=4....
How to improve that?
How about this? Went and tested, to be sure :)
<?php
$new_get = $_GET; // clone the GET array
$new_get['pagenum'] = $i; // change the relevant parameter
$new_get_string = http_build_query($new_get); // create the foo=bar&bar=baz string
?>
<a class="page-numbers" href="?<?php echo $new_get_string; ?>">
<?php echo $i ?>
</a>
Also, note that the whole $href bit is unnecessary. If you start your href with ?, the browser will apply the query string to the current path.
I bet you're going to be looping, though, so here's a version optimized for producing 10,000 page number links. My benchmarks put it as being ever so slightly faster at large numbers of links, since you're just doing string concatenation instead of a full HTTP query build, but it might not be enough to be worth worrying about. The difference is only really significant when there five or six GET parameters, but, when there are, this strategy completes in about half the time on my machine.
<?php
$pageless_get = $_GET; // clone the GET array
unset($pageless_get['pagenum']); // remove the pagenum parameter
$pageless_get_string = http_build_query($pageless_get); // create the foo=bar&bar=baz string
for($i = 0; $i < 10000; $i++):
// append the pagenum param to the query string
$page_param = "pagenum=$i";
if($pageless_get_string) {
$pageful_get_string = "$pageless_get_string&$page_param";
} else {
$pageful_get_string = $page_param;
}
?>
<a class="page-numbers" href="?<?php echo $pageful_get_string; ?>">
<?php echo $i ?>
</a>
<?php endfor ?>
$url = $_SERVER['REQUEST_URI'];
$urlparams = parse_url($url);
if(isset($urlparams['query']){
parse_str($urlparams['query'],$vars);
$vars['pagenum'] = $i;
$urlparams['query'] = http_build_query($vars);
} else {
$urlparams['query'] = 'pagenum='.$i;
}
$url = http_build_url($urlparams);
//http_build_url() is in PECL, you might need to manually rebuild the
//url by looping through it's components:
/*
$url=(isset($urlparams["scheme"])?$urlparams["scheme"]."://":"").
(isset($urlparams["user"])?$urlparams["user"]:"").
(isset($urlparams["pass"])? ":".$urlparams["pass"]:"").
(isset($urlparams["user"])?"#":"").
(isset($urlparams["host"])?$urlparams["host"]:"").
(isset($urlparams["port"])?":".$urlparams["port"]:"").
(isset($urlparams["path"])?$urlparams["path"]:"").
(isset($urlparams["query"])?"?".$urlparams["query"]:"").
(isset($urlparams["fragment"])?"#".$urlparams["fragment"]:"");
*/

Categories