1

我正在创建一个 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

4 回答 4

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";
}
于 2013-06-07T04:39:41.083 回答
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";
    }
}
于 2013-06-07T04:36:46.703 回答
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";
}
?>

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

于 2013-06-07T04:44:10.493 回答
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";
 }
于 2013-06-07T04:47:39.527 回答