Apologies if this question is duplicated, I have however not found an obvious answer to my question. I am a complete novice with php , be kind! When I load the following code, it appears to run if(isset($_POST['test']))
even though I have not pressed the button "test"
. I only want the code to execute when I press the " test
" button. How do I resolve this?
<?php
if(isset($_POST['update'])) {
$content=simplexml_load_file("books.xml");
$value=$content->book->price;
$sum=$content->book->price;
}
if(isset($_POST['test'])) {
$content=simplexml_load_file("books.xml");
$value=$content->book->price;
$content->book->price = $value + 1.0;
$content->asXML("books.xml");
$sum=$content->book->price;
}
?>
<body>
<form method="post">
<input type="checkbox" id="i1check1" onchange="toggleDisabled(this.checked)"> Alarm 01
<input type="text" id="i1text1" name="i1" size="80" maxlength="128" value="<?php echo @$sum;?>"/>
<input type="submit" id="i1btn1" name="update" value="Update"/>
<input type="submit" id="i1btn2" name="test" value="Test"/>
</form>
<script>
function toggleDisabled(_checked) {
document.getElementById('i1text1').disabled = _checked ? false : true;
document.getElementById('i1btn1').disabled = _checked ? false : true;
}
</script>
</body>
Please Try This
if(isset($_POST['update']) && $_POST['update'] == "Update"){
$content=simplexml_load_file("books.xml");
$value=$content->book->price;
$sum=$content->book->price;
}
if(isset($_POST['test']) && $_POST['test'] == "Test"){
$content=simplexml_load_file("books.xml");
$value=$content->book->price;
$content->book->price = $value + 1.0;
$content->asXML("books.xml");
$sum=$content->book->price;
}
In your case, you should use !empty instead of isset .
Whenever form is submitted, all form's name attributes will be received in $_POST array. It doesn't matter either it is set or not.
You can do filtration using !empty because it will check set + has value . While isset check only set .
if(!empty($_POST['update'])){ // !empty instead of isset
$content=simplexml_load_file("books.xml");
$value=$content->book->price;
$sum=$content->book->price;
}
if(!empty($_POST['test'])){ // !empty instead of isset
$content=simplexml_load_file("books.xml");
$value=$content->book->price;
$content->book->price = $value + 1.0;
$content->asXML("books.xml");
$sum=$content->book->price;
}
Suggestion :- You have written echo @$sum;
in form. Never hide your errors using @ . Instead of doing this, you should ON error_reporting in development mode.
You should write that statement as below.
echo empty($sum) ? '' : $sum; // ternary operator
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.