Reputation: 186
So basically I have a simple form and I want to change the input boxes text different every time you press submit by using PHP. I know my code doesn't work but I don't understand how to solve this problem. Maybe the array is not the best way to do this?
<body>
<?php
if(isset($_GET['submit'])) exit();
$msg= ['One', 'Two', 'Three', '']
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="submit" name="submit" value="Paina nappi">
<input type="text" name="msg" value="<?php echo (isset($msg)) ? $viesti : ''; ?>">
</form>
</body>
Upvotes: 1
Views: 195
Reputation: 52
You could write something like this:
<?php
session_start();
$msgArray= array('One', 'Two', 'Three', '');
// if $_SESSION['msgIndex'] is not set, we initialize it, or it will take 0 value every loading page
if (!isset($_SESSION['msgIndex'])) { $_SESSION['msgIndex'] = 0; }
if (isset($_GET['submit'])) {
getMessage();
}
// We save msgIndex in a $_SESSION variable cause even if the user reload the page, we keep the value
function getMessage() {
if ($_SESSION['msgIndex'] >= 0) {
$_SESSION['msgIndex'] += 1;
} if ($_SESSION['msgIndex'] > 3) {
$_SESSION['msgIndex'] = 0;
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="submit" name="submit" value="Paina nappi">
<input type="text" name="msg" value="<?= $msgArray[$_SESSION['msgIndex']] ?>">
</form>
Upvotes: 1