[英]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. 我有一个带有提交按钮的输入字段名称(id,设置,值)的表单。 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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.