我有一个表单,其中包含输入字段名称(id,settings,value)和提交按钮。现在,我正在将表格数据插入到数据库中我想从第一次插入数据时那么第二次如何更新相同的表格数据Wthout插入数据..
<?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 ;
}
答案 0 :(得分:1)
您需要查询表以检查该值是否存在。如果记录不存在,则插入它,否则更新它。
<?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";
}