<?php
error_reporting(0);
$dbh = new PDO("mysql:host=localhost;dbname=test", "root", "");
/*
--
-- Table structure for table `contacts`
--

CREATE TABLE `contacts` (
  `id` int(5) NOT NULL,
  `fullname` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `contacts`
--

--
-- Indexes for dumped tables
--

--
-- Indexes for table `contacts`
--
ALTER TABLE `contacts`
  ADD PRIMARY KEY (`id`);
*/
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$fullname = $_POST["fullname"];
$phone = $_POST['phone'];
$email = $_POST['email'];
if (isset($_POST['comments'])){
$comments  = addslashes(nl2br($_POST['comments']));
}
}
$function = 'Enter';
//update
if ($_POST['submit'] == 'Update'){
    $newupdateid = $_POST['updateid'];
     $updatesql = $dbh->prepare("update contacts set fullname = '$fullname',phone='$phone',email='$email',comments='$comments',lastmodified=now() where id = $newupdateid");
    $updatesql->execute();
     echo $fullname.' updated! '; 
    //print_r($updatesql->errorInfo());
} 




//insert
if ($_POST['submit'] == 'Enter'){
    
    $inssql = $dbh->prepare("insert into contacts (fullname,phone,email,comments,lastmodified) values ('$fullname','$phone','$email','$comments',now())");
    $inssql->execute();
    echo 'Record added!';
} 

//delete
if ($_GET['deleteid']){
    $delid = $_GET['deleteid'];
    $delsql = $dbh->prepare("delete from contacts where id = '$delid'");
    $delsql->execute();
    echo $_GET['fullname']." Deleted";
}



//show contacts
$sql = $dbh->prepare("select * from contacts");
$sql->execute();
while ($row = $sql->fetch()){
  $id = $row['id'];    
  echo $row['fullname'].' <a href="contactscms.php?fullname='.$row['fullname'].'&deleteid='.$id.'" onclick= "return confirm(\'are you sure you want to delete '.$row['fullname'].'? \')">Delete</a> <a href="contactscms.php?updateid='.$id.'">Update</a><br>';   
}

//populate value
if ($_GET['updateid']){
   $upid = $_GET['updateid'];
   $function = 'Update';    
   $upsql = $dbh->prepare("select fullname,phone,email,comments from contacts where id = '$upid'");
   $upsql->execute();
   $uprow = $upsql->fetch();
   $upname = $uprow['fullname'];
   $upemail = $uprow['email'];
   $upphone = $uprow['phone'];   
   $upcomments = $uprow['comments'];            

echo '<a href="contactscms.php">&lt;&lt;Return to add mode</a>';    
}


?>


<form action = "<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Name: <input type="text" name="fullname" value="<?php 
if (isset($upname)){
    echo $upname;
}?>" required ><br>
Phone: <input type="tel" name="phone" value="<?php echo $upphone;?>" required ><br>
Email: <input type="email" name="email" value="<?php echo $upemail;?>" required ><br>
Comments: <textarea name="comments"><?php echo $upcomments;?></textarea> <br>  
<input type="hidden" name="updateid" value ='<?php echo $upid;?>'>   
<input type="submit" name="submit" value = "<?php echo $function;?>"> 
</form>
    