Reputation: 45
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 ;
}
Upvotes: 0
Views: 2706
Reputation: 842
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";
}
Upvotes: 1