为什么我不能使用REPLACE.How如何更新表中的行或者如果它不存在则插入它?

时间:2017-02-22 12:48:41

标签: php mysql database

我想在表中更新一行,或者如果它不存在则插入它?

我已经从这个链接中读取了解决方案。 How do I UPDATE a row in a table or INSERT it if it doesn't exist?

所以,我使用了替换,但它没有用。它只在表中添加了新行,但没有更新任何内容。 enter image description here

这是我的结构 enter image description here

<?php

define('ROOTPATH', __DIR__);
$output = [];
$output['result'] = [];
$output['image_path'] = [];
$applicationName = (isset($_POST) && array_key_exists('applicationName', $_POST)) ? $_POST['applicationName'] : 'applicationName';

if (empty($applicationName)) {
    $output['result'][] = 'missing application name';
}
else if (is_array($_FILES) && array_key_exists('image', $_FILES) && array_key_exists('logo', $_FILES))
{

    $upload_dir  = '/upload_dir/';
    $upload_path = ROOTPATH . $upload_dir;

    $applicationName = $_POST['applicationName'];

    $sql_field_list  = ['applicationName'];
    $sql_value_list  = [$applicationName];

    foreach ( $_FILES as $key => $upload) {

        if($key != 'image' && $key != 'logo')
        {
            $output['result'][] = $key . ' is invalid image';
        }
        else
        {

            if ($upload['error'] == UPLOAD_ERR_OK &&
                preg_match('#^image\/(png|jpg|jpeg|gif)$#', strtolower($upload['type'])) && //ensure mime-type is image
                preg_match('#.(png|jpg|jpeg|gif)$#', strtolower($upload['name'])) ) //ensure name ends in trusted extension
            {
                $parts     = explode('/', $upload['tmp_name']);
                $tmpName   = array_pop($parts);
                $fieldname = ($key == 'image') ? 'bgBNPage' : 'logo';
                $filename  = $applicationName . '_' . $fieldname . '.' . pathinfo($upload["name"], PATHINFO_EXTENSION);

                if (move_uploaded_file($upload["tmp_name"], $upload_path . $filename))
                {

                    $sql_field_list[] = $fieldname;
                    $sql_value_list[] = $upload_dir . $filename;

                    $output['image_path'][$key] = $upload_dir . $filename;
                }
                else
                {
                    $output['result'][] = $key . ' upload fail';
                }

            }
            else
            {
                $output['result'][] = $key . ' error while upload';
            }
        }

    }

    //after upload complete insert pic data into database

    $con = mysqli_connect("localhost", "root", "root", "museum");

    if (!$con) {
       echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $fields = implode(', ', $sql_field_list);
    $values = implode("', '", $sql_value_list);
    $sql = "REPLACE INTO general (" . $fields . ") VALUES ('" . $values . "');";

    if (!mysqli_query($con, $sql)) {
        die('Error: ' . mysqli_error($con));
    }

    mysqli_close($con);


} else {

    $output['result'][] = 'no file selected';
}

    header('Content-type: application/json');
    echo json_encode($output);
    echo json_encode('finish');

?>

我可以使用

if(logo or bgBNPage is enpty)
{
insert into database
}
else{
Update database
}

请告诉我正确的语法。

2 个答案:

答案 0 :(得分:0)

我猜是用户名是字段,如果它是重复的,你想要更新。因此,如果用户名是唯一键,您可以执行以下操作:

insert into general ([fields]) values ([values])
on duplicate username update
[whatever]

答案 1 :(得分:0)

我找到了解决方案。 我使用if else条件来证明它。 这是我的代码结果

    //after upload complete insert pic data into database
    $con = mysqli_connect("localhost", "root", "root", "museum");
    $sql = "SELECT logo,bgBNPage FROM general "; 
    $result = mysqli_query($con, $sql); 


    if (!$con) {
       echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $fields = implode(', ', $sql_field_list);
    $values = implode("', '", $sql_value_list);

    if(mysqli_num_rows($result) > 0) 
    {
        $str_array = [];
        for($i =0; $i < count($sql_field_list); $i++) 
        {
            $str_array[] = $sql_field_list[$i] . "='" .  $sql_value_list[$i] ."'";
        }

        $sql = 'UPDATE general SET ' . implode(',', $str_array);
        //$sql = "UPDATE general SET (" . $fields . ") = ('" . $values . "');";
    }
    else 
    {
        $sql = "INSERT INTO general (" . $fields . ") VALUES ('" . $values . "');";
    }


    if (!mysqli_query($con, $sql)) {
        die('Error: ' . mysqli_error($con));
    }

    mysqli_close($con);