doucha5080 2014-04-04 16:09
浏览 12
已采纳

为什么mysql不告诉我重复是什么?

I have a simple table, two columns and one primary key. Here's the PHP I use to populate the table:

$query = "INSERT INTO alt_upcs (sku, upc) VALUES (".$upc[0].",\"".$upc[1]."\")";
mysqli_query($link, $query);
if ($error = mysqli_error($link))
{
  if (preg_match("+DUPLICATE+i", $error))
  {
    $errQuery = "SELECT * FROM alt_upcs WHERE upc LIKE ".$upc[1];
    $result = mysqli_query($link, $errQuery);
    $errRow = mysqli_fetch_row($result);
    echo "Duplicate UPC found: ".$upc[1]." exists for skus ".$errRow[0]." and ".$upc[0].".
";
  }
  else
  {
    echo $error."
$query
";
  }
}

The $upc array is created from an input file containing lines that start with a sku followed by up to 7 upcs. In some rare cases there are more than one sku with the same UPC and in even rarer cases a single sku can have the same UPC twice. The code above works fine for the former, I get the error message Duplicate UPC found: xxxx exists for skus yyyy and zzzz.

But, when there is a sku with two UPCs, and the above block of code runs for the second UPC, I get Duplicate UPC found: xxxx exists for skus and zzzz.

Obviously, MySQL recognizes the duplicate, so why does the error query not show it?

Some additional info, upc is my unique key (primary index) and I can query the table manually and see the value I am attempting to get in my script

Thanks to Bogdan for leading me to my error: I was using LIKE because the field type (which I neglected to share) is varchar and I didn't encapsulate the string $upc[1] insite of double quotes - MySQL thinks I was sending it an int because the string is numeric , which chops off any leading zeros.

Either of these work, but the second is what I should be doing.

  $errQuery = "SELECT * FROM alt_upcs WHERE upc = ".$upc[1];

This works because MySQL comparing the integer value of the field with the integer value of `$upc[1]

  $errQuery = "SELECT * FROM alt_upcs WHERE upc LIKE \"".$upc[1]."\"";

Properly enclosing the string is what I meant to do to begin with.

  • 写回答

2条回答 默认 最新

  • douzhangshao6369 2014-04-04 16:35
    关注

    Your $errQuery is going to be:

    SELECT * FROM alt_upcs WHERE upc LIKE foo
    

    This is a syntax error - the value after the LIKE should be quoted:

    SELECT * FROM alt_upcs WHERE upc LIKE 'foo'
    

    Although if you're not going to apply any wildcards, you ought to use a direct equality check:

    SELECT * FROM alt_upcs WHERE upc='foo'
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错