未定义的变量:第14行的C:\ xampp \ htdocs \ CRUD \ login.php中的con

时间:2014-08-27 08:32:03

标签: php

<?php

    $con = mysqli_connect('localhost', 'root', '', 'crud_db');
    if (mysqli_connect_errno()) 
    {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    function signin() 
    {
      $session_start;
      if (!empty($_POST['email'])) 
      {
        echo "not empty";
        $query = "SELECT * FROM 'employee' where email= '$_POST ['email']' AND password=   '$_POST ['pwd']'";
        $result = mysqli_query($con, $query);
        $row = mysqli_fetch_array($result);

        if (!empty($row['email']) AND !empty($row['password'])) {
            echo "successfully login";
        } else {
            echo "login fail";
      }
    }

    }

    if (isset($_POST['submit'])) 
    {
      signin();
    }
?> 

我是php的新手,我正在尝试创建一个简单的登录页面 这是我的PHP代码,一个简单的登录PHP代码。 当我尝试运行代码时,我得到一个错误 注意:未定义的变量:第14行的C:\ xampp \ htdocs \ CRUD \ login.php中的con 我已经在第一行定义了变量$ con,那么为什么我会收到此错误。

第二 - 当我尝试运行sinin功能块时,我得到一个错误 警告:mysqli_fetch_array()期望参数1为mysqli_result,在第15行的C:\ xampp \ htdocs \ CRUD \ login.php中给出null 这意味着什么,我该如何解决这个问题。

3 个答案:

答案 0 :(得分:0)

您可以在函数内部使其全局化,或者在参数中传递它以访问它

$con = mysqli_connect('localhost', 'root', '', 'crud_db');
if (mysqli_connect_errno()) 
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

function signin($con) 
{
  session_start();
  if (!empty($_POST['email'])) 
  {
    echo "not empty";
    $query = "SELECT * FROM employee where email= '$_POST ['email']' AND password=   '$_POST ['pwd']'";
    $result = mysqli_query($con, $query);
    $row = mysqli_fetch_array($result);

    if (!empty($row['email']) AND !empty($row['password'])) {
        echo "successfully login";
    } else {
        echo "login fail";
  }
}

}

if (isset($_POST['submit'])) 
{
  signin($con);
}
?> 

答案 1 :(得分:0)

与问题无关,但是:

 $query = "SELECT * FROM 'employee' where email= '$_POST ['email']' AND password=   '$_POST ['pwd']'";

无效。

$query = "SELECT * FROM 'employee' where email= '{$_POST ['email']}' AND password=   '{$_POST['pwd']}'";

会起作用,但它仍然是sql注入漏洞。

阅读How can I prevent SQL injection in PHP?

答案 2 :(得分:0)

将数据库端和功能端写入不同的php脚本,就像这样可以工作

<?php 
$con = mysqli_connect('localhost', 'root', '', 'crud_db');
?>

function.php
<?php
include('database.php');
function signin() 
{
global $con;
  session_start();
  if (!empty($_POST['email'])) 
  {
    echo "not empty";
    $query = "SELECT * FROM employee where email= '$_POST ['email']' AND password=   '$_POST ['pwd']'";
    $result = mysqli_query($con, $query);
    $row = mysqli_fetch_array($result);

    if (!empty($row['email']) AND !empty($row['password'])) {
        echo "successfully login";
    } else {
        echo "login fail";
  }
}

}


?>