2016-06-21 94 views
0

我試圖將密碼或移動無效語句的輸出顯示到HTML頁面。這裏是我的代碼:在HTML中調用PHP變量

<?php 
    session_start(); 
    if(isset($_POST['register'])) { 
    $phone = ($_POST['tphone']); 
    $upass = ($_POST['tpassword']);  
    if ([email protected]_match('/^(?=.*\d{3,})(?=.*[A-Za-z]{5,})[[email protected]#$%]{8,32}$/', $upass)) { 
     $upass = 'You have enter an invalid password'; 
    } 
    else if ([email protected]("^[0-9]{3}-[0-9]{7}$", $phone)) { 
     $mobile = 'Invalid mobile' 
    } 
    } 
?> 
<html> 
    <body> 
    <p><?php echo $upass ?>.</p> 
    <form method="post"> 
     <input type="text" name="tphone" placeholder="First Name" class="form-name" required> 
     <input type="password" name="tpassword" placeholder="Last Name" class="form-name2" required> 
     <button type="submit" name = "register" class="btn-register">Register</button> 
    </form> 
    </body> 
</html> 

這裏的問題是我應該如何使用PHP變量在我HTML像我已經定義$upassp標籤內。我還想在單擊註冊按鈕時設置此變量。

現在當我echo $upass,它顯示Undefined variable時,我沒有選擇註冊按鈕。

+1

可能的[如何從HTML或Javascript調用PHP文件]的重複(http://stackoverflow.com/questions/20637944/how-to-call-a-php-file-from-html-or-javascript ) –

+3

'ereg'已被棄用/死亡/消失。你不應該在任何新的代碼中使用它,並且使用'@'是PHP的等同物,將你的手指塞進你的耳朵,然後「lalalalalala聽不到你」。 –

+0

[PHP:「Notice:Undefined variable」和「Notice:Undefined index」]的可能重複(http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) –

回答

0

只需將錯誤消息分配給一個變量,然後檢查該變量是否不爲空。如果它中包含字符串值,則顯示<p>,其中包含錯誤消息。

<?php 
session_start(); 
$errorMessage = null; 

if (isset($_POST['register'])) { 
    $phone = $_POST['tphone']; 
    $upass = $_POST['tpassword'];  

    if ([email protected]_match('/^(?=.*\d{3,})(?=.*[A-Za-z]{5,})[[email protected]#$%]{8,32}$/', $upass)) { 
     $errorMessage = 'You have enter an invalid password'; 
    } elseif ([email protected]("^[0-9]{3}-[0-9]{7}$", $phone)) { 
     $errorMessage = 'Invalid mobile' 
    } 
} 
?> 
<html> 
<body> 
    <?php if ($errorMessage) { ?> 
     <p><?php echo $errorMessage; ?></p> 
    <?php } ?> 
    <form method="post"> 
     <input type="text" name="tphone" placeholder="First Name" class="form-name" required> 
     <input type="password" name="tpassword" placeholder="Last Name" class="form-name2" required> 
     <button type="submit" name = "register" class="btn-register">Register</button> 
     </form> 
</body> 
</html> 
+0

與此問題是,它仍然顯示無效的密碼,即使沒有觸發一個按鈕 – xodebox95

0

您需要了解在Web服務器上運行PHP以生成發送到瀏覽器的HTML頁面。

這意味着當PHP完成運行時,當用戶收到它的輸出。如果您需要在用戶操作後發生某些事情,那麼必須在前端(瀏覽器)中執行某些操作才能觸發它,通常使用JavaScript。

如果您希望前端發回數據或在Web服務器上查詢某些內容,則需要使用AJAX(或其變體)或WebSockets以允許來自瀏覽器的JavaScript將請求直接傳遞給Web服務器不重新加載頁面。