【问题标题】:PHP Variables Are Always NullPHP 变量始终为空
【发布时间】:2018-09-20 19:36:02
【问题描述】:

我正在尝试创建一个 php 登录页面,并将用户名和密码输入捕获到 html 文本框中。但我的问题是我的 echo 语句总是为变量返回 null。

为什么没有设置这些变量?

<?php
  include("config.php");
  session_start();

  if($_SERVER["REQUEST_METHOD"] == "POST") {
      $myusername = mysqli_real_escape_string($db,$_POST['username']);
      $mypassword = mysqli_real_escape_string($db,$_POST['password']); 
      echo $myusername;
      echo $mypassword;
  }
?>
<html>   
<head>
  <title>Login Page</title>      
  <style type = "text/css">
     body {
        font-family:Arial, Helvetica, sans-serif;
        font-size:14px;
     }
     label {
        font-weight:bold;
        width:100px;
        font-size:14px;
     }
     .box {
        border:#666666 solid 1px;
     }
  </style>      
   </head>   
   <body bgcolor = "#FFFFFF">             
           <form action = "" method = "post">
              <label>UserName:</label><input type = "text" name = "username" class = "box"/><br /><br />
              <label>Passwore:</label><input type = "password" name = "password" class = "box" /><br/><br />
              <input type = "submit" value = " Submit "/><br />
           </form>
</body>
</html>

编辑
这是我使用 mysqli_connect() 的 config.php

<?php
 define('DB_SERVER', 'localhost:3036');
 define('DB_USERNAME', 'user');
 define('DB_PASSWORD', 'pass');
 define('DB_DATABASE', 'db');
 $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>

【问题讨论】:

  • 您确定表单上的操作参数必须为空吗?
  • @SalmonKiller 空白动作表示使用当前 URL 作为动作。
  • var_dump($_POST) 显示什么?
  • 如果您还没有连接到数据库,即通过mysqli_connect,那么mysqli_real_escape_string函数将不起作用。这是你的问题。
  • 您在第二行 define 上的引用不正确。你有一个弯引号而不是直引号。

标签: php


【解决方案1】:

您不能像这样在服务器名称中指定端口号。根据文档中的this comment,它适用于外部主机名,但在使用localhost 时不起作用。您需要使用可选的端口参数。

 define('DB_SERVER', 'localhost');
 define('DB_USERNAME', 'user');
 define('DB_PASSWORD', 'pass');
 define('DB_DATABASE', 'db');
 define('DB_PORT', 3036);
 $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE,DB_PORT);

【讨论】:

  • 就是这样 - 将端口添加到它自己的定义中会使代码正常运行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-05
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 1970-01-01
  • 2021-07-07
相关资源
最近更新 更多