搜索现有数据,如果php,请加倍

时间:2014-01-14 10:45:48

标签: php mysql

我正在网页上工作,我希望有一个可能的删除按钮,其工作方式如下:

 - you introduce a country ISO code which you want to delete
 - click the button
 - if the country has players participating (competitor table, ISO_country_code column) then prints the message that this cannot happen
 - if not, deletes the country from country table

我尝试了以下方式,但我不知道如何创建第二个条件,以实现适当的工作。

$connect=mysqli_connect("localhost","root","","mydatabase");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
 else 
 {
    $result=mysqli_query($connect,"SELECT COUNT(*) FROM competitor
        WHERE ISO_country_code='".$_POST['countrycode']."')")
    if ($result>0)
    {
        echo 'The following country is involved with players, so it can not be deleted!</br></br>';
    }
    else (mysqli_query($connect,"DELETE FROM country WHERE     ISO_country_code='".$_POST['countrycode']."'"));
    {
        echo 'The following country was deleted: '.$_POST["countrycode"]."</br>";
    }
}       

3 个答案:

答案 0 :(得分:0)

你有一些语法错误+可能没有得到你正在寻找的行数。

$connect=mysqli_connect("localhost","root","","mydatabase");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
 else 
 {
    $result=mysqli_query($connect,"SELECT * FROM competitor
        WHERE ISO_country_code='".$_POST['countrycode']."'");
     $rows = mysql_num_rows($result);
    if ($rows>0)
    {
        echo 'The following country is involved with players, so it can not be deleted!</br></br>';
    }
    else {
      mysqli_query($connect,"DELETE FROM country WHERE ISO_country_code='".$_POST['countrycode']."'");
        echo 'The following country was deleted: '.$_POST["countrycode"]."</br>";
  }
}  

答案 1 :(得分:0)

你的$result不包含任何整数,它返回true或false(或使用面向对象方式时的对象)。

如果您想查看查询返回的结果数量,则必须使用mysqli_num_rows($result)函数替换$ result。

您应该查看prepared statements以防止SQL注入。

首先,您必须使用以下命令创建查询的预准备语句:

$stmt = mysqli_prepare($connect,"SELECT * FROM competitor WHERE ISO_country_code=?");

然后将参数绑定到语句(s代表“String”):

mysqli_stmt_bind_param($stmt,"s",$_POST['countrycode']);

执行你的陈述:

mysqli_stmt_execute($stmt);

然后,您可以使用mysqli_stmt_fetch($stmt)获取结果。

答案 2 :(得分:0)

试试这个..

if(mysql_num_rows($result) > 0)
    {
    echo "cannot delete";
    }
    else if(mysql_num_rows($result) == 0)
    {
     //write the query for deletion
    echo "deleted";
    }