无法访问if语句中的变量

时间:2014-02-11 09:40:52

标签: php

我正在尝试使用此代码,以便能够在我的预订系统中停止双重预订。当您输入两次相同的时间时,它会出现此错误:

Email is validthis time is already booked
Notice: Undefined variable: sql in C:\xampp\htdocs\book.php on line 44

Warning: mysqli_query(): Empty query in C:\xampp\htdocs\book.php on line 44
Error:

这是我的代码

<?php

//$error = ""; // Initialize error as blank
$con=mysqli_connect("localhost","","","");


if (mysqli_connect_errno($con))
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") 
{
    $email = $_POST['email'];
    $time = $_POST["time"];
    $name = $_POST["name"];
    $surname = $_POST["surname"];
    $date = $_POST["date"];
    $adl1 = $_POST["adl1"];
    $adl2 = $_POST["adl2"];
    $postcode = $_POST["postcode"]; 

    if(!filter_var(($email), FILTER_VALIDATE_EMAIL))
    {
        echo "E-mail is not valid";
    } 
    else 
    {
        echo "Email is valid";

        $result = mysqli_query($con, "SELECT time FROM tbl_booking WHERE time = '$time'") or trigger_error("Query Failed! SQL: $result - Error: ".mysqli_error($con), E_USER_ERROR);
        if(mysqli_num_rows($result) == 0) 
        {
            $sql="INSERT INTO tbl_booking (name, surname, email, date, time, adl1, adl2, postcode) VALUES ('$name','$surname','$email','$date','$time','$adl1','$adl2','$postcode')";

        } 
        else 
        {
            echo("this time is already booked");
        }

        if (!mysqli_query($con, $sql))
        {
            die('Error: ' . mysqli_error($con));
        }

        mysqli_close($con);
    }
}

基本上我认为它试图访问$sql语句中的if,但我不知道它为什么不能。除非我是傻瓜。

3 个答案:

答案 0 :(得分:0)

将$ sql设为“global” - &gt;你只需要在if语句之前创建它。

答案 1 :(得分:0)

您可以将代码重写为,因为在其他情况下,mysqli_query()没有查询,这就是您收到错误的原因,

if(mysqli_num_rows($result) == 0){
     $sql="INSERT INTO tbl_booking (name, surname, email, date, time, adl1, adl2, postcode) VALUES ('$name','$surname','$email','$date','$time','$adl1','$adl2','$postcode')";
     mysqli_query($con, $sql) or die('Error: ' . mysqli_error($con));
 } else {
     echo("this time is already booked");
  }

答案 2 :(得分:-1)

尝试在您的代码未执行的PHP代码之上声明$ sql值

 if(mysqli_num_rows($result) == 0) 
        {
            $sql="INSERT INTO tbl_booking (name, surname, email, date, time, adl1, adl2, postcode) VALUES ('$name','$surname','$email','$date','$time','$adl1','$adl2','$postcode')";

        } 

这个条件它实际上正在执行你的其他正文,它为什么会产生$ sql变量未定义的异常