使用mysqli_num_row错误检查重复项

时间:2014-11-11 12:30:44

标签: php mysqli

我正在为项目构建一个Inventory页面,当我尝试插入一个新项目(如果它已经在数据库中)时,我正在尝试检查。我遇到了mysqli_num_rows函数的一个问题,它要求一个参数。我很确定我的查询事先是有效的,所以我不明白为什么这样做。是因为查询返回0行?以下是代码。

我也在使用mysqli_connect的include,所以它不在下面的代码中。

<?php
if(isset($_POST["product_name"])){
$product_name = mysqli_real_escape_string($link,$_POST["product_name"]);
$price = mysqli_real_escape_string($link,$_POST["price"]);
$category = mysqli_real_escape_string($link,$_POST["category"]);
$subcategory = mysqli_real_escape_string($link,$_POST["subcategory"]);
$details = mysqli_real_escape_string($link,$_POST["details"]);

$sql = mysqli_query($link,"SELECT id FROM products WHERE product_name = '$product_name'");

if(mysql_num_rows($sql) > 0){
echo "sorry you tried to add a duplicate <a href = Inventory_list.php> Click here </a>";
exit();
}

$sql = mysqli_query($link, "INSERT INTO products       (product_name,price,details,category,subcategory,date_added)
VALUES('$product_name','$price','$details','$category',
'$subcategory',now())") or die("Update Error: ".mysqli_error());
$pid = mysqli_insert_id();
$newname = $pid.jpg;
move_uploaded_file($_FILES['fileField']['tmp_name'],"../Images/$newname");
}

?>

1 个答案:

答案 0 :(得分:0)

变化

if(mysql_num_rows($sql) > 0){
echo "sorry you tried to add a duplicate <a href = Inventory_list.php> Click here </a>";
exit();
}

if(mysqli_num_rows($sql) > 0){
echo "sorry you tried to add a duplicate <a href = Inventory_list.php> Click here </a>";
exit();
}