<?php
include 'connection.php';
//insert data!!!!!
$submit = $_POST['submit'];
$fullname = $_POST['fullname'];
$idtoupdate = $_POST['updateid'];
$deleteid = $_GET['deleteid'];
$btnstatus = 'Enter Name';
if ($submit == 'Enter Name'){
  
    //this prepares a statement
   $insertsql = $dbh->prepare("insert into crud_contacts (fullname) values ('$fullname') ");
    //this executes
    $insertsql->execute();
    echo $fullname." has been inserted<br>";
    
}

//delete data!!!!!!
if (isset($deleteid) && is_numeric($deleteid)){
   $delsql =  $dbh->prepare("delete from crud_contacts where id = '$deleteid'");
    $delsql->execute();
    //print_r($delsql->errorInfo());
    echo 'Record deleted<br>';
    
    
} 


//update data!!!!!
if (isset($idtoupdate) && is_numeric($idtoupdate)){
   $updatesql = $dbh->prepare("update crud_contacts set fullname = '$fullname' where id = '$idtoupdate'");
    $updatesql->execute();
    echo 'record updated<br>';
}



$updateid = $_GET['updateid'];
if (isset($updateid) && is_numeric($updateid)){
    $btnstatus = "Update Name";
 $upsql  =  $dbh->prepare("select fullname from crud_contacts where id = '$updateid'");  
 $upsql->execute();   
    $uprow = $upsql->fetch();
    $upfullname = $uprow['fullname'];
    
    
}



//display data!!!!!!
$displaysql = $dbh->prepare("select id,fullname from crud_contacts");
$displaysql->execute();
while ($row = $displaysql->fetch()){
    $id = $row['id'];
    $fullname = $row['fullname'];
    echo $fullname.' <a href = "crud.php?deleteid='.$id.'" onclick="return confirm(\'Are you sure you want to delete '.$fullname.'?\')">Delete</a> <a href = "crud.php?updateid='.$id.'">Update</a><br>';
}
    


?>

<form action = "crud.php" method="post">
<input type="text" name="fullname" value="<?php echo $upfullname;?>"><br>
<input type="hidden" name="updateid" value = "<?php echo $updateid;?>">    
<input type="submit" name="submit" value="<?php echo $btnstatus;?>">
</form>
<?php
if (!empty($updateid)){
echo '<a href = "crud.php">Back to add mode</a>';
}
