PHP:检查数据库中的项是否具有相同的名称

时间:2013-06-07 04:35:03

标签: php mysql database if-statement

我正在创建一个PHP脚本,用于检查您的数据库是否包含具有相同名称的元素。这是代码:

<?php

$query = @mysql_query("SELECT * FROM category");

while($Row = mysql_fetch_array($query)) {
    $ID = $Row['id'];
    $Name = $Row['name'];
}

// fetch the value of the name field
$CategoryName = $_GET['name'];

if($CategoryName === $Name) {
    echo "here is an element with the same name";
}

?>

为什么不起作用?错误在哪里?对不起我的英语,我是意大利人。

4 个答案:

答案 0 :(得分:3)

如果您只想知道元素是否存在,则可以将查询更改为更有效。

$query = mysql_query("SELECT COUNT(Name) FROM category WHERE Name = '" . mysql_real_escape_string($_GET['name']) . "'");
$row = mysql_fetch_array($query);
if ($row[0]) {
  echo "here is an element with the same name";
}

答案 1 :(得分:2)

如果从数据库返回多个项目,则需要将逻辑包装在while

// fetch the value of the name field
$CategoryName = $_GET['name'];

while($Row = mysql_fetch_array($query)) {
    $ID = $Row['id'];
    $Name = $Row['name'];

    if($CategoryName === $Name) {
        echo "here is an element with the same name";
    }
}

答案 2 :(得分:0)

使用以下代码:

$query = @mysql_query("SELECT * FROM category");

$flag = false; // I am using a flag variable

// fetch the value of the name field
$CategoryName = $_GET['name'];

 while($Row = mysql_fetch_array($query)) {
    $ID = $Row['id'];
    $Name = $Row['name'];
    if($CategoryName === $Name) {
       $flag = true;
    }
}

if($flag) {
    echo "here is an element with the same name";
}
?>

这也是检查数据库中名称的技巧。

答案 3 :(得分:0)

我认为优化方式是使用mysql中的count聚合函数来匹配与给定名称匹配的行数。这可以通过两种方式完成。

$query = mysql_query("SELECT COUNT(Name) FROM category WHERE Name = '" .      mysql_real_escape_string($_GET['name']) . "'");
 $row = myqsl_fetch_array($query);
 if ($row[0]) {
      echo "here is an element with the same name";
   }

或由此

$query = mysql_query("SELECT Name FROM category WHERE Name = '" .      mysql_real_escape_string($_GET['name']) . "'");
 $row = mysql_num_rows($query);
 if ($row>0) {
      echo "here is an element with the same name";
 }