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

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.

Related

(PHP) How do I properly concatenate a list of arrays into a string for file_put_contents?

I've been playing around with a php input function that will build a html page for a game, something like a wiki. All is going fine and dandy but when trying to build an array into a string it's passing back some funny errors.
It's happening to every one that involves an array and I've snipped some code out that works independently to save me time, but just can't figure it out. I'm using the Linux Terminal to run the script and when I set it to echo inside the foreach loop it does it just fine, it just won't when I try building it into a HTML file.
Here is the input script:
echo "\nHow many ranks were there (number)?:\n";
$facInputRankLimit = readline();
echo "Please read carefully and supply the ranks in descending order (HIGHEST > LOWEST):\n";
$facInputRankCount = 0;
$facInputRankString = "";
while ($facInputRankCount < $facInputRankLimit) {
echo "Enter a rank:\n";
$facInputRanks[$facInputRankCount] = readline();
$facInputRankCount++;
}
foreach ($facInputRanks as $facInputRankList) {
$facInputRankString .= $facInputRankList.PHP_EOL;
}
Then I'll build it into a multi-line echo (rather than appending every single block of code):
$facBuildPage = <<<EOT
<?php
\$facRankLimit = '$facInputRankLimit';
\$facRanks = '$facInputRankString';
include('faction2.html');
?>
EOT;
The variables with the backslashes will then be built into "$facFileName.php" and will be a set of variables inputted through this script (input2.php), which will each also include the same html page.
To top it off I'm getting really weird results... if I create 5 ranks, each as "1 2 3 4 5", I actually get "1 2 3" with two vertical linebreaks in between.
Edit: Snipped some of it, I didn't want to risk not adding enough info but it turns out I added a bit much.
For instance, the input I'm giving is:
$facInputRankLimit = 5;
$facInputRanks[1] = 1; -> $facInputRanks[5] = 5;
But it prints:
1<br><br>2<br><br>3
#Deepkak - The relative code in faction2.html is:
<div class="fpDivisions fpBox">
<span class="header">Ranks</span><br>
<?php
$facRankCount = 0;
while ($facRankCount < $facRankLimit) {
echo $facRanks[$facRankCount].'<br>';
$facRankCount++;
}
?>
</div>
I Hope this will solve the issue
<?php
echo "\nHow many ranks were there (number)?:\n";
$facInputRankLimit = readline();
echo "Please read carefully and supply the ranks in descending order (HIGHEST > LOWEST):\n";
$facInputRankCount = 0;
while ($facInputRankCount < $facInputRankLimit) {
echo "Enter a rank:\n";
$facInputRanks[$facInputRankCount] = readline();
$facInputRankCount++;
}
$array = [];
foreach ($facInputRanks as $facInputRankList) {
$array[] = "'".$facInputRankList."'";
}
$facInputRankString = "[".implode(",",$array)."]";
$facBuildPage = <<<EOT
<?php
\$facRankLimit = '$facInputRankLimit';
\$facRanks = $facInputRankString;
include('faction2.html');
?>
EOT;
echo $facBuildPage;
I've created a workaround for this, incase anyone needs any help in the future. It was as simple as echoing it from the HTML page, rather than creating a loop that runs through both the PHP script and the HTML code.
PHP input code:
echo "\nHow many ranks were there (number)?:\n";
$facInputRankLimit = readline();
echo "Please read carefully and supply the ranks in descending order (HIGHEST > LOWEST):\n";
$facInputRankCount = 0;
while ($facInputRankCount < $facInputRankLimit) {
echo "Enter a rank:\n";
$facInputRanks[$facInputRankCount] = readline();
$facInputRankCount++;
}
$facInputList = implode("<br>", $facInputRanks);
PHP output code:
$facBuildPage = <<<EOT
<?php
\$facRanks = '$facInputList';
include('faction2.html');
?>
EOT;
file_put_contents("test/$facFileName.php", $facBuildPage);
HTML output code:
<div class="fpDivisions fpBox">
<span class="header">Ranks</span><br>
<?php echo $facRanks; ?>
</div>

preg_replace of php code

I am writing an application that will look at a single record, obtain values from about 12 flags (0 or 1), look up those flags against a status table (in MySQL) and return a variable called $status_message which is in that table.
In this table I need to have hyperlinks (working fine) but also echo some variables, i.e.
You have no bids for {{$row->_item_name}}
or
View this item now by clicking here
Now I need item name and the other example to be translated into <?php echo $row->_item_name; ?>
I have tried a preg_replace with the following:
<?php
$find = array('/{{/', '/}}/');
$replace = array('<?php echo ', ' ?>');
echo preg_replace($find, $replace, $status_message);
?>
but this is not working.
Can anyone advise how I can get the desired result and 'echo' the variable in the MySQL field?
Had a brainwave. Much simpler,
instead of $row->_item_name I just put {{itemname}} in the string. I then use the following code:
<?php
$message_buyer = str_replace('{{itemname}}', $row->_item_name , $message_buyer);
echo $message_buyer;
?>
so no need to have <?php calls in the string at all.

Showing the first element in an foreach array in HTML

I have an array $category['transactions']. It stores data as follow:
ID Name Phone
1 Test Test2
2 Test3 Test4
It's because I use the same array for different purpose, at one of the scenario is to show only the first record in this array. I don't what to change the coding in php nor creating a different parameter. What can I improve based on the following coding in html to get the first record only in this array?
<?php foreach($category['transactions'] as $transaction) { ?>
<div><?php echo $transaction['id']; ?></div>
<div><?php echo $transaction['name']; ?></div>
<?php } ?>
replace your code with.
<?php $firstRow=reset($category['transactions']);
echo '<div>',$firstRow['id'],'</div>';
echo '<div>',$firstRow['name'],'</div>';
?>
You don't need to iterate through the array to get the first element.
You don't even need the foreach to get the first element. Just use array_values():
$first = array_values($category['transactions')[0]
try this..
<?php
foreach($category['transactions'] as $transaction)
{
echo $transaction['id'];
break;
}
?>
and no need to use multiple php tags...

Better way to create html code from php variables?

My website consists of many products that are each contained in a div with the id content block. The link, image, background, description and price are all loaded from a mySQL table. My original plan was to save the below html code as a string and loop over the rows in the mySQL table filling the string I created with php/mySQL values.
I was wondering if I am going about this the right way, or is there a better way to create html code from php variables?
<div id="contentblock" style="background-image:url(images/$BACKGROUND.png);">
<div id="picture"><img src="$IMAGELINK"/></div>
<div id="description"><p>$DESCRIPTION</p></div>
<div id="price"><p class=price>$PRICE</p></div>
</div>
Firstly PHP is a template engine - in my experience template engines that layer ontop of PHP are only good for the simplest of cases and are easily outgrown.
Secondly the original code is as good as any method. At risk of stating the obvious to make it better abstract it into a function;
function output_block($BACKGROUND, $LINK, $IMAGELINK, $DESCRIPTION, $PRICE)
{
echo "<div id='contentblock' style='background-image:url(images/$BACKGROUND.png);'>
<div id='picture'><a href='$LINK'><img src='$IMAGELINK'/></a></div>
<div id='description'><p>$DESCRIPTION</p></div>
<div id='price'><p class=price>$PRICE</p></div>
</div>";
}
If you want to make it much better then adopt a framework, an entire admin config page is show below. All of the HTML glue is provided by the framework - the following code is real, but really to illustrate how a framework can provide a lot of the grunge work for you.
In the example below if I want to edit a single entity I'd change the TableViewEdit into a FormView and provide an instance of an entity rather than an iterable list.
$entity = new CbfConfig(); // Database entity
$page = new AdminWebPage("Site Configuration"); // Page for output
/*
* build the view
*/
$vil = new ViewItemList();
$col = &$vil->add(new ViewItem("description","Description"));
$col->get_output_transform()->allow_edit(false); // this field cannot be editted
$col = &$vil->add(new ViewItem("value","Value"));
$v1 = new TableViewEdit($entity, $vil,"admin_values"); // present as standard editable table
/*
* output the page
*/
$page->begin();
$iterable_list = CbfConfig::site_begin();
$page->add_body($v1->get_output($iterable_list,'admin_config'));
$page->end();
Id just have all my html code outside of php tags, then whereever I need a variable from php do as follows
<div id="description"><p><?php echo $DESCRIPTION; ?></p></div>
You can loop around non php code too. For example
<?php
for($i = 0; $i < 10; $i++) {
?>
<div id="description"><p><?php echo $i; ?></p></div>
<?php
} //end for loop
?>
Obviously this is just an example.
well if im without a template engine for somereason i usually do something like:
function partial($file, $args = array()) {
extract($args);
ob_start();
include($file);
return ob_get_clean();
}
Really, there are 3 ways of doing this. Use whichever is easiest for you in the context that you are using it in.
<?php
while(($row=mysql_fetch_assoc($result))!==false)
{
echo "<div>{$row['fieldName']}</div>";
}
?>
<?php
while(($row=mysql_fetch_assoc($result))!==false)
{
echo '<div>'.$row['fieldName'].'</div>';
}
?>
<?php
while(($row=mysql_fetch_assoc($result))!==false)
{
?>
<div><?= $row['fieldName']; ?></div>
<?php
}
?>

Add value to variable PHP

I am creating a category list.. 20 different categories and when they click and send a category it will pass a numeric value representing the category to the Database..
For example:
<option value="1">Apple</option>
<option value="2">Microsoft</option>
The reason for that I am passing a numeric value in the database, is because I have more than 1 language on the webpage, and I have different label files. I would like to echo a php variable based on the category number.
<? echo $ct_1; ?>
But to avoid a lot of if/else statements, I would like to know if I could add the number to the variable. So if I am looping the category to be this: $row['category'] I would like to add that variable to the other one.. Like so:
<? $category = $.'ct_'.$row['category']; echo $category; ?>
I know that is not possible.. But I hope you get my idea and maybe have a solution for this.
This is called variable variables.
$category = ${'ct_'.$row['category']};
echo $category;
Or just:
echo ${'ct_'.$row['category']};
     
A tailored variable variableDocs example:
<?php $category = 'ct_'.$row['category']; echo $$category; ?>
If you look closely it's nearly identival to yours:
<?php $category = $.'ct_'.$row['category']; echo $category; ?>
^ ^
You COULD use eval() but that can lead to some very big security holes.
I suggest using an array instead:
$ct = array(1 => "Apple", 2 => "Microsoft");
echo $ct[$row['category']];
Quick and dirty approach would be to use eval
eval('$category = $ct_'. $row['category'] . ';');
echo $category;
Make sure input is sanitized first!

Categories