user2154027 user2154027 - 1 month ago 17
PHP Question

Add and edit in one form php

I have two files .. addclient.php & Editclient.php.

I want to combine in one php form. can u please help me to do this

<?php
if(isset($_GET['id'])) {
$id = $_GET['id'];
echo "add";
} else if(isset($_GET['id'])) {
$id = $_GET['id'];
echo "edit"
}
?>


if
$id
already exist in the table than the row is updated otherwise it's an
INSERT
.
If you only have an
$id
: show the form with existing data in it.
If it's not a
$id
isn't populated : show an empty form.

Ali Ali
Answer
<?php
    if(isset($_GET['id'])) {
         $id = intval($_GET['id']);
         $stmt = $mysqli->prepare("SELECT id FROM table WHERE id = ?");
         $stmt->bind_param('i', $id);
         $stmt->execute();
         if($stmt->num_rows > 0) {
               // UPDATE
               // Text field with the id
               echo '<input type="text" name="id" value="'. $id. '"/>';
         } else {
               // INSERT
               // Text field with no id
               echo '<input type="text" name="id"/>';
         }
    }
?>

This validates the integer and makes sure it's one, queries the table for that specific id, if there is more than one row with that id then you need to update, else you need to insert.

Comments