[英]Using isset or is not set with variable in PHP?
我有一個提交數據的表格,作為測試,我試圖首先檢查是否在提交時設置了變量。 如果設置了變量,將顯示一個文本,說明“設置了變量”。 但是,如果未設置,則將顯示一個文本,顯示“未設置變量”,一旦未設置變量,則應進行設置,因此下次提交表單時,將顯示變量,但是未設置為我工作,由於某種原因,它總是顯示未設置變量,我的PHP代碼如下:
<?php
if (isset($test)) {
echo "This var is set";
}
if (!isset($test)) {
echo "This var is not set";
$test = 'set';
}
?>
<form action="" method="post">
<input type="text" id="text" name="text" autocomplete="off"><br><br>
<input type="submit" value="submit">
</form>
我無法完成似乎如此簡單的事情,真是太愚蠢了,我只是在學習並且嘗試着自學,謝謝您提供的任何幫助!!!
如果您使用表單提交值,請嘗試使用此表單,
if (isset($_POST['text'])) {
echo "This var is set";
}
if (!isset($_POST['text'])) {
echo "This var is not set";
$test = 'set';
}
否則,如果變量設置為空值,例如$test = '';
(這意味着已設置變量,但沒有值)僅if
有條件的情況下將執行您的第一個變量。
工作代碼和說明:
<?php
$test="";
if (isset($_POST["text"])) { //always directly check $_POST,$_GET var without assigning
echo "This var is set";
$test=$_POST["text"]; // then assign
}
else{ // and use else clause for otherwise case
echo "This var is not set";
$test = 'set'; // AND if you want set to default/custom value in case of not set.
}
?>
<form action="" method="post">
<input type="text" id="text" name="text" autocomplete="off">
<br /><br />
<input type="submit" value="submit">
</form>
您尚未聲明變量$test
。
除非您還沒有在此處包含一些PHP,否則您的變量為空。 提交表單后,輸入將添加到$ _POST數組(對於method = "post"
)或$ _GET數組(對於method = "get"
)。
修理:
<?php
if (isset($_POST['text'])) {
$test = $_POST['text'];
echo "This var is set";
}
if (!isset($_POST['text'])) {
echo "This var is not set";
$test = 'set';
}
?>
<form action="" method="post">
<input type="text" id="text" name="text" autocomplete="off"><br><br>
<input type="submit" value="submit">
</form>
<?php
$test=$_GET["text"];
if (isset($test)) {
echo "This var is set";
}
if (!isset($test)) {
echo "This var is not set";
$test = 'set';
}
?>
<form action="#" method="get">
<input type="text" id="text" name="text" autocomplete="off"><br><br>
<input type="submit" value="submit">
</form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.