mysql插入/更新总是插入从不更新

时间:2014-05-07 09:41:05

标签: php mysql

如果某个行与给定的part_code不存在,则插入以下代码;如果part_code已存在,则更新。问题是它总是插入并产生重复。任何人都可以看到原因。

    $query = 'SELECT * FROM qty_csv';  
$result = mysqli_query($conn,$query);

if (!$result) {
    die(mysqli_error($conn));
}   
while($row = mysqli_fetch_array($result)){
    $part_code          = $row['code'];
    $part_descr         = $row['descr'];
    $part_qty_in_stock  = $row['qty_in_stock'];
    $reorder_level      = $row['reorder_level'];
    $reorder_qty        = $row['reorder_qty'];
    $part_price         = $row['price'];

        // check to see if the value you are entering is already there      
        $result1 = $conn->query("SELECT * FROM part WHERE part_code == '$part_code'");
        if (!$result1){ 
            $sql = 
                    "INSERT INTO part  VALUES (
                            '',
                            '',
                            '$part_descr',
                            '$part_price',
                            '',
                            '$part_code',
                            '',
                            '',
                            '',
                            '',
                            '$reorder_level',
                            '$reorder_qty',
                            '',
                            '',
                            '$part_qty_in_stock',
                            '',
                            '',
                            ''
                            )";
            if (!$conn->query($sql)) {
                echo "INSERT failed: (' . $conn->errno . ') " . $conn->error;
            }    
        }else{
            $sql = "UPDATE part SET "
                    . "part_qty_in_stock    = '$part_qty_in_stock',"
                    . "reorder_level        = '$reorder_level',"
                    . "reorder_qty          = '$reorder_qty' "
                    . "WHERE part_code == '$part_code'";
            // This code exists and will be updated
            $conn->query($sql);
        }    
  }

我在调试器下有它,看到即使part_code == '$part_code' $result1是bool()false。我本以为它是真的。

3 个答案:

答案 0 :(得分:1)

请检查您的查询,请使用=代替==

进行检查
SELECT * FROM part WHERE part_code = '$part_code'

答案 1 :(得分:1)

使用

$result1 = $conn->query("SELECT count(*) as count FROM part WHERE part_code = '$part_code'");

然后只需检查$result1['count'] > 0

答案 2 :(得分:1)

这里的问题是你的" $ result1"只有在发生错误时,object才为False,否则,即使查询没有返回任何结果(因为它是空的),它也将是一个mysqly对象。

你应该检查行数,而不仅仅是检查!$ result。

只需更改

if (!$result1){ 

if (mysqli_num_rows($result1) == 0){ 

查看文档以获取更多信息:

http://it1.php.net/mysqli_query

http://www.php.net/manual/en/mysqli-result.num-rows.php