Idan Hazan Idan Hazan - 5 months ago 18
PHP Question

changing the url by post method in php

I'm trying to change the url path by submited form...

index.php



<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<?php include 'file.php'; ?>
<form action=<?php action(); ?> method="post">
<fieldset>
<legend>Choose ID by select tag</legend>
<label>ID:</label>
<select name="id" onchange="this.form.submit()">
<?php option(); ?>
</select>
<label><?php selcet(); ?></label>
</fieldset>
</form>
</body>
</html>


file.php



<?php

function action() {
$value = $_SERVER['PHP_SELF'];

if (isset($_POST['id'])) {
$value .= '?id=' . $_POST['id'];
}

echo $value;
}

function option() {
$count = 3;

for ($i = 1; $i <= $count; $i++) {
$value = 1;

if (isset($_POST['id'])) {
$value = $_POST['id'];
}

if ($i == $value) {
echo '<option value="' . $i . '" selected>' . $i . '</option>';
}
else {
echo '<option value="' . $i . '">' . $i . '</option>';
}
}
}

function selcet() {
$value = 1;

if (isset($_POST['id'])) {
$value = $_POST['id'];
}

echo 'Option ' . $value . ' selected.';
}

?>


the action() function not working as well, I'm getting wrong ids, I want to get ?id=2 while '2' selected.

Can someone help me please? Thanks! :)

Answer

To achieve your original request:

[...] I want to get ?id=2 while '2' selected.

You need to use GET not POST for the easiest and fastest results.

index.php

<?php include 'file.php'; ?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <form action="<?php echo active(); ?>" method="GET">
            <fieldset>
                <legend>Choose ID by select tag</legend>
                <label>ID:</label>
                <select name="id" onchange="this.form.submit()">
                    <?php echo option(); ?>
                </select>
                <label><?php echo select(); ?></label>
            </fieldset>
        </form>
    </body>
</html>

file.php

<?php
function active() {
    $value = $_SERVER['PHP_SELF'];
    if (isset($_GET['id'])) {
        $value .= '?id=' . $_GET['id'];
    }
    return $value;
}

function option() {
    $count = 3;
    for ($i = 1; $i <= $count; $i++) {
        $value = 1;
        if (isset($_GET['id'])) {
            $value = $_GET['id'];
        }
        if ($i == $value) {
            echo '<option value="' . $i . '" selected>' . $i . '</option>';
        }
        else {
            echo '<option value="' . $i . '">' . $i . '</option>';
        }
    }
}

function select() {
    $value = 1;
    if (isset($_GET['id'])) {
        $value = $_GET['id'];
    }
    return 'Option ' . $value . ' selected.';
}
?>
Comments