2

我的代码中使用了一条if语句,但是代码的逻辑不起作用,因为我想要的是,当用户输入城市名称而不输入地区名称时,系统必须显示错误消息

并且当用户输入城市名和区名而不输入经纬度时,系统必须显示错误信息。

在我的代码中发生的情况是,即使用户输入城市和经度,系统也会显示错误消息,通知用户输入经度和经度

代码:

if($_POST['city'])
{
    $city = $_POST['city'];
    $lat = $_POST['lat'];
    $long = $_POST['long'];

    if($_POST['dist'] =="")
    {
        $errorMSG = "you can not add city without having relation with district";
    }
    if($lat || $long ==""){ $errorMSG = "You can not add village Without its coordination";}
    else
    {
        $sql = mysql_query("INSERT INTO village (id, village_name, district_id, lattitude, longitude)VALUES('', '$city', , '$lat',  '$long')")or die(mysql_error());
        echo $city;
    }
}
4

3 回答 3

3

if($lat || $long =="")应该if($lat=="" || $long =="")

于 2013-05-21T08:14:50.210 回答
2

改变这个: -

if($lat || $long =="")

if($lat =="" || $long =="")

解释 :-

您所做的是检查 $lat 是否为空或 $long 是否为空。了解运算符的优先级。== 的优先级高于 ||

于 2013-05-21T08:15:03.083 回答
2

您的代码容易受到 SQL 注入的攻击。
并且其中存在一些逻辑错误。

使用PDO的正确代码是

if($_POST['city'])
{
    $errorMSG = '';
    $city = $_POST['city'];
    $lat  = $_POST['lat'];
    $long = $_POST['long'];
    $dist = $_POST['dist']

    if(!$dist)
    {
        $errorMSG .= "you can not add city without having relation with district";
    }
    if(!$lat || !$long)
    {
        $errorMSG .= "You can not add village Without its coordination";
    }

    if (!$errorMSG)
    {
        $sql = "INSERT INTO village VALUES(NULL, ?, ?, ?, ?)";
        $pdo->prepare($sql);
        $pdo->execute(array($city,$dist,$lat,$long));

    }
}
于 2013-05-21T08:28:01.830 回答