如何只用一个按钮插入和更新数据?

时间:2017-03-15 09:21:47

标签: php html mysql

在第一次单击按钮时,它将数据添加到数据库,然后在第二次单击时按钮将更新数据。有人知道如何操作..我有一个插入代码,但它无法更新。

here is my html code
<html>
<head>
<body>
<form method="POST" action="example.php">
<label>Content:</label>
<br>
<textarea name="cafnrcontent" id="cafnrcontent" rows="6" cols="43"></textarea>
</div>
<br>
<label>Posting:</label>
<br>
<label>From date:</label>
<input type="date" name="cafnrstart_date">
<label>To date:</label>
<input type="date" name="cafnrend_date">
<br><br>
  <input type="file" name="cafnrimage">
<br><br>
<label>Submitted by:</label>
<input type="text" id="cafnrauthor" name="cafnrauthor" value="">
<br>
<br>
<input type="submit" id="send" name="send" value="Submit">
</form>
</body>
</head>
</html>

<?php
include 'dbconnect.php';

  if(isset($_POST['send']))
{

$cafnrcontent =
mysqli_real_escape_string($DBcon,strip_tags($_POST['cafnrcontent'])); 
$cafnrimage = mysqli_real_escape_string($DBcon,strip_tags($_POST['cafnrimage']));
  $cafnrstart_date = mysqli_real_escape_string($DBcon,strip_tags($_POST['cafnrstart_date']));
  $cafnrend_date = mysqli_real_escape_string($DBcon,strip_tags($_POST['cafnrend_date']));
  $cafnrauthor = mysqli_real_escape_string($DBcon,strip_tags($_POST['cafnrauthor']));

     $Query = "INSERT INTO example (cafnrcontent,cafnrimage,cafnrstart_date,cafnrend_date,cafnrauthor) VALUES('$cafnrcontent','$cafnrimage','$cafnrstart_date','$cafnrend_date','$cafnrauthor')";

    $run = mysqli_query($DBcon, $Query);
             if (!$run) {
                echo 'Query Failed ';
            }
          }

有人能告诉我一个例子吗?请帮我。在此先感谢:)

1 个答案:

答案 0 :(得分:1)

示例:

<a href="manage_user.php?action=add_new">Add New</a>
<a href="manage_user.php?action=edit&user_id=<?php echo $row['usrm_id']; ?>" >Edit</a>

<?php if(isset($_GET['action']) && ($_GET['action'] == "add_new")) 
{?>
    <input type = "submit" class = "btn btn-primary" style="width:49%" value = "Save" name = "submit">
<?php
}
else
{?>
    <input type = "submit" class = "btn btn-primary" style="width:49%" value = "Update" name = "submit">
<?php 
} ?>

如果您想要使用此代码的示例,您将能够以相同的形式显示不同的按钮。首先尝试创建表单然后如果发生任何错误,那么我们在这里解决您的问题。如果你不尝试,你将无法学习。

你的插入查询应该是这个:

INSERT INTO example (`cafnrcontent`,`cafnrimage`,`cafnrstart_date`,`cafnrend_date`,`cafnrauthor`) VALUES('".$cafnrcontent."','".$cafnrimage."','".$cafnrstart_date."','".$cafnrend_date."','".$cafnrauthor."')