【发布时间】:2012-09-22 02:13:30
【问题描述】:
我正在尝试编写一个脚本来将 XML 文件中的值插入 SQL 数据库。
但是我无法让脚本正确检查 SQL 数据库中是否已存在值。
这是我当前的代码:
$result=mysql_query("SELECT * FROM `categories_description` WHERE categories_name`='$qCategory'");
if (mysql_num_rows($result) > 0){
echo "cat exists";
}
else if($qCategory != ""){
mysql_query("INSERT INTO `categories` (`categories_id`, `categories_image`, `parent_id`, `sort_order`, `date_added`, `last_modified`, `categories_status`) VALUES ('$catid', NULL, '0', NULL, NULL, NULL, '1');");
mysql_query("INSERT INTO `categories_description` (`categories_id`, `language_id`, `categories_name`, `categories_description`) VALUES ('$catid', '1', '$qCategory', '$qCategory');");
$catid +=1;
}
我已经尝试了很多方法来让它发挥作用,但它就是不想这样做。 我遇到的问题是,如果我有重复的值,它无论如何都会插入它。 有谁知道如何解决这一问题?还是出了什么问题? 非常感谢。
【问题讨论】:
-
我在您的代码中发现的最大错误是您没有进行任何错误检查。 Mysql 返回错误并给出描述。但是您没有使用这些功能,因此您独自坐在黑暗中。 tuxradar.com/practicalphp/19/8/6
-
请不要使用
mysql_*函数编写新代码。它们不再维护,社区已经开始deprecation process。看到red box?相反,您应该了解prepared statements 并使用PDO 或MySQLi。如果你不能决定哪一个,this article 会帮助你。如果你选择 PDO,here is good tutorial。