<?php
// Errors are turned on. Warning and notices too if there are any issues with the script or connection
error_reporting(0);

    // below calls the database by its location
    // In this case it's 'localhost' from MAMP and 'webd-166_books' database
    // AND username 'root' and password 'root'
    // Localhost should work with most servers
    // AND Only pass and user change along with database name
$dbh = new  PDO("mysql:host=localhost;dbname=books", "root", "");    
$button = 'Enter Books';
// Delete
//http://localhost/books.php?deleteid=1
$deleteid = $_GET['deleteid'];
if ($deleteid){
    $delsql = $dbh->prepare("delete from books where id = '$deleteid'");
    $delsql->execute();
}

// Update

// Create
$submit = $_POST['submit'];   
$title = $_POST['title'];
$author = $_POST['author'];

if ($submit == 'Enter Books'){
  
    
    // BELOW for PDO this 'prepare' mysql variable is defined as astatement that prepares the information entered into the form from their specified variables - $title, $authro
    
    // The code below will always need to be used for this
    // Only difference will be what is inside of the quoted (insert) statement
    $mysql=$dbh->prepare("insert into books (title,author) values ('$title','$author')");
    
    // Below is showing was is being entered into form

    
    // BELOW the 'prepare' state will be followed by this 'execute' statement
    $mysql->execute();
    
    // BELOW will print any errors with the $mysql variable
    //print_r($mysql->errorInfo());
  
}

$updateid = $_GET['updateid'];

//Update
if ($submit == 'Update Books'){
 $mysql=$dbh->prepare("update books set title = '$title',author='$author' where id = '$updateid'");
 $mysql->execute();    
}
if ($updateid){
        $button = 'Update Books';
      $upsql = $dbh->prepare("select * from books where id = '$updateid'");
      $upsql->execute();
       $uprow = $upsql->fetch(); 
       $uptitle = $uprow['title'];
       $upauthor = $uprow['author'];    
    
}
    // Read
if ($updateid != ''){
    echo '<a href ="books.php"><< BACK TO ADD MODE</a><br> 
';
}  
$sql = $dbh->prepare("select * from books"); 
$sql->execute();
while ($row = $sql->fetch()){
    $id = $row['id'];
    $title = $row['title'];
    $author = $row['author'];
    echo $title.'-'.$author.'  <a href="books.php?deleteid='.$id.'" onclick="return confirm(\'Are you sure?\');">Delete</a> <a href="books.php?updateid='.$id.'">Update</a><br>';
}




?>

<form action="books.php?<?php echo $_SERVER['QUERY_STRING'];?>" method="post">
   <label>Title:</label><input type="text" name="title" value="<?php echo $uptitle;?>" required>
   <br>
   <label>Author:</label><input type="text" name="author" value="<?php echo $upauthor;?>" required>
   <br>
   <input type="submit" name="submit" value="<?php echo $button;?>">
</form>