2016-06-21 27 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服务器不重新加载页面。