简体   繁体   中英

PHP- how to insert form data first time and second time update same data

I have a form having input field name (id,settings,value) with submit button. Now, I am inserting form data into database now I want that when from data inserting first time then how to update same form data second time Wthout insert data..

    <?php 
    if(isset($_POST['save']))
    {
    include "connection.php" ;

    $id = $_POST['id'] ;
    $name = $_POST['name'] ;
    $value   = $_POST['value'] ;

$query="create table if not exists settings(id int(10),name varchar(50),value varchar(100))";
$results=mysql_query($query) or die("QUERY FAILED 1:".mysql_error());   

$query="INSERT INTO settings VALUES('$id','$name','$value')"; 
$results=mysql_query($query) or die("QUERY FAILED 2:".mysql_error());


 $query="update settings set value='$value' where id='$id'";
 $results=mysql_query($query) or die("QUERY FAILED 3:".mysql_error());



     echo $settings ;

    }

You need query the table to check whether the value is exists or not. If the record is not exists, then insert it, else update it.

<?php
    if(isset($_POST['save']))
    {
    include "connection.php" ;
    $id = $_POST['id'] ;
    $name = $_POST['name'] ;
    $value   = $_POST['value'] ;

    $query="create table if not exists settings(id int(10),name varchar(50),value varchar(100))";
    $results=mysql_query($query) or die("QUERY FAILED 1:".mysql_error());


    // pass the name and check whether the value is exists or not,
    $result = mysql_query("SELECT * FROM settings WHERE name = '".$name."'");
    $number_of_rows = mysql_num_rows($result);

    // if number of rows is 0, then insert it. else update it
    if($number_of_rows == 0){
        $query="INSERT INTO settings VALUES('$id','$name','$value')";
    } else{
        // get the row id
        $data_row = mysql_fetch_row($result);
        $record_id = $data_row[0];
        $query="UPDATE settings SET value='".$value."' WHERE id = '".$record_id."'";
    }

    $results=mysql_query($query) or die("QUERY FAILED 2:".mysql_error());

     echo "Record inserted/updated";
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM