<?
$dbh = new PDO("mysql:host=localhost;dbname=mmaaaco_ksecor", "mmaaaco_ksecor", "hamilton");
$create = $dbh->prepare("CREATE TABLE IF NOT EXISTS books (
  id int(5) NOT NULL auto_increment,
  bookname varchar(255) NOT NULL,
isbn varchar(255) NOT NULL,
author varchar(255) NOT NULL,
price varchar(255) NOT NULL,
  PRIMARY KEY  (id)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1");
$create->execute();
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?
//insert from form
$name = $_POST['bookname'];
$isbn = $_POST['isbn'];
$author = $_POST['author'];
$price = $_POST['price'];
$deleteid = $_GET['deleteid'];
$editid = $_GET['editid'];
$status = 'Add Record';


//this is your insert statment (Create!)
if (strlen($name) > 2 && !$editid) {
$insertsql = $dbh->prepare("insert into books (bookname,isbn,author,price values (?,?,?,?)");
$insertsql->execute(array($name,$isbn,$author,$price));
print_r($insertsql->errorInfo());//<--this is how to troubleshoot errors
echo '<br/>'.$name.' added!<br/>';
	
}

if ($editid != '' && strlen($name) > 3){
$upsql = $dbh->prepare("update books set bookname = ?, isbn = ?, author = ? , price =?  where id = ?");
$upsql->execute(array($name,$isbn,$author,$price,$editid));
echo '<br/>Record Updated!</br>';
}


if ($deleteid){
	$deletesql = $dbh->prepare("delete from books where id = ?"); 
		$deletesql->bindParam(1,$deleteid, PDO::PARAM_INT,5);
    $deletesql->execute();
	if ($deletesql) echo $deleteid.' has been deleted!<br/>' ;
}

if ($editid){
	$editsql = $dbh->prepare("select bookname,isbn,author,price from books where id = ?");
	$editsql->bindParam(1,$editid, PDO::PARAM_INT,5);
    $editsql->execute();
	$editrow = $editsql->fetch();
	$nametoedit = $editrow['bookname'];
	$isbntoedit = $editrow['isbn'];
	$authortoedit = $editrow['author'];
	$pricetoedit = $editrow['price'];
	$status = 'Edit Record';
}





$selectsql = $dbh->prepare("select id,bookname from books");
$selectsql->execute();
while ($row = $selectsql->fetch()){
	echo '<a href = "bookscms.php?id='.$row['id'].'">'.$row['bookname'].'</a>
	<a href = "bookscms.php?deleteid='.$row['id'].'" onclick="return confirm(\'Are you sure you want to delete '.$row['bookname'].'\');">Delete</a>         <a href = "bookscms.php?editid='.$row['id'].'">Edit</a><br/>';
}

$dbh->null;

?>
<form action = "<?= $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];?>" method="post">
Name: <input type="text" name = "bookname" value = "<?= $nametoedit; ?>"><br/>
isbn: <input type="text" name = "isbn" value = "<?= $isbntoedit; ?>"><br/>
author: <input type="text" name = "author" value = "<?= $authortoedit; ?>"><br/>
price: <input type="text" name = "price" value = "<?= $pricetoedit; ?>"><br/>

<input type = "submit" name = "submit" value = "<?= $status;?>"/>   <br/>
</form>
<?
if ($editid) echo '<br/><a href = "bookscms.php">Back to add mode</a><br/>';

?>

</body>
</html>
