Jimmy Jimmy -4 years ago 155
PHP Question

Pass form value to function to get array value

I'm really struggling with this at the moment, and I have read several tutorials to try and get my head around it. I have my code working fine with the text input box, but I'm trying to pass the radio box to my function as well and use it to get my array value.

I will implement things like form validation and sanitisation later, but now I just want to be able to output the array result within my function, depending on what radio button was selected. This is the code I have tried:

index.php

<?php
if (isset($_POST['submit'])) {
$data = $_POST['name']; // the data from text input.
$colour = $_POST['colour']; // data from colour radio.
}
?>
...
<form action="/app.php" method="post">
<input type="text" name="name">
<input name="colour" type="radio" value="1">Red
<input name="colour" type="radio" value="2">Blue
<input name="colour" type="radio" value="3">Green
<input type="submit" name="submit" value="Submit">
</form>
<img src="pngfile.php?data=<?php print urlencode($data);?>">


pngfile.php

<?php
require_once 'functions.php';
$textdata = urldecode($_GET['data']);
$colourdata = urldecode($_GET['colour']);
process($textdata,$colourdata);
exit;
?>


functions.php

<?php

/* Generate Image */
function process($textdata, $colourdata)
{

$colour_array = [
"1" => "#9E2A2B",
"2" => "#3E5C76",
"3" => "#335C67",
];
...


I am stuck with the piece of the code that will take the radio button value (1/2/3) and then look up the eqivalent array value and output the colour, i.e:
if radio button with value 1 is selected, then we output
1#9E2A2B
.

Any help would be really appreciated.

Answer Source
<form action="/app.php" method="post">

form method POST not GET

$_GET['colour'] edit to $_POST['colour']

in function

function process($textdata, $colourdata)
{

$colour_array = [
    "1" => "#9E2A2B",
    "2" => "#3E5C76",
    "3" => "#335C67",
];

$color = isset($colour_array[$colourdata]) ? $colour_array[$colourdata] : false;
...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download