<?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`);
*/
$function = 'Enter';
//update
if ($_POST['submit'] == 'Update'){
    $fullname = $_POST["fullname"];
    $newupdateid = $_POST['updateid'];
    $updatesql = $dbh->prepare("update contacts set fullname = '$fullname' where id = $newupdateid");
    $updatesql->execute();
    //print_r($updatesql->errorInfo());
} 




//insert
if ($_POST['submit'] == 'Enter'){
    $fullname = $_POST["fullname"];
    $inssql = $dbh->prepare("insert into contacts (fullname) values ('$fullname')");
    $inssql->execute();
} 
//delete
if ($_GET['deleteid']){
    $delid = $_GET['deleteid'];
    $delsql = $dbh->prepare("delete from contacts where id = '$delid'");
    $delsql->execute();
}



//show contacts
$sql = $dbh->prepare("select * from contacts");
$sql->execute();
while ($row = $sql->fetch()){
  $id = $row['id'];    
  echo $row['fullname'].' <a href="contactscms.php?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 from contacts where id = '$upid'");
   $upsql->execute();
   $uprow = $upsql->fetch();
   $upname = $uprow['fullname'];
echo '<a href="contactscms.php">&lt;&lt;Return to add mode</a>';    
}


?>


<form action = "contactscms.php" method="post">
Name: <input type="text" name="fullname" value="<?php echo $upname;?>" ><br>
<input type="hidden" name="updateid" value ='<?php echo $upid;?>'>   
<input type="submit" name="submit" value = "<?php echo $function;?>"> 
</form>
    