<?php
include '/home/mmaaaco/public_html/wdm3304materials/wdm3304week2/dbconnect.php';//this connects to the db with a refenceable object: $dbh
//$dbh = new PDO("mysql:host=localhost;dbname=mmaaaco_jmoreland", "mmaaaco_jmorelan", "jmoreland361521");
//insert
$status = 'Enter Name';//for the button value 
$deleteid = $_GET['deleteid'];//gets the query string when the user clicks delete lnk
$fullname = $_POST['fullname'];//fullname field from the form via post method
$editid = $_GET['editid'];//if edit link is clicked
$submit = $_POST['submit'];//submit button pressed


//if delete is clicked 
 if (is_numeric($deleteid)){  //is the url value a number? 
 $delsql = $dbh->prepare("delete from contacts where id = ?");//prepare statement
 $delsql->bindValue(1,$deleteid);//bind the value of the variable to the ?
 $delsql->execute();//run it
if ($delsql) echo 'Record Deleted<br/>';//$delsql is boolean...did it work?
 }



//edit block!
if ($submit == 'Edit Name'){//tests value of dynamic button
$updatesql = $dbh->prepare("update contacts set fullname = ? where id = ?");//update statement
$updatesql->execute(array($fullname,$editid));//an array because more than one ?
if ($updatesql) echo 'Record updated!<br/>';//confirmation
}

//insert block
if ($submit == 'Enter Name'){
//$insql = $dbh->prepare("insert into contacts (fullname) values ('$fullname')"); 
//bind value for security:
$insql = $dbh->prepare("insert into contacts (fullname) values (?)"); //prepared statement
$insql->bindValue(1,$fullname);//one value
$insql->execute();//run it

  if ($insql) echo 'Record Inserted <br/>';//confirm
  else print_r($insql->errorInfo());//how to error handle!!!!!!
}

//this is the block to populate the text field with the id of what is being edited...note $editid 
if (is_numeric($editid)){
$status = 'Edit Name';
$upsql = $dbh->prepare("select fullname from contacts where id = ?");
$upsql->bindValue(1,$editid);
$upsql->execute();
$uprow = $upsql->fetch();
$upfullname = $uprow['fullname'];//a variable to put in the text field so the user can edit!
}


//display records!!
$sql = $dbh->prepare("select id,fullname from contacts");
$sql->execute();
while($row = $sql->fetch()){//fetches records in a loop 
$id = $row['id'];//get id to display in links
$fullname = $row['fullname'];//get id to display name
echo $fullname.'   <a href = "cmsorig.php?deleteid='.$id.'" 
onclick="return confirm(\' Are you sure you want to delete '.$fullname.'\');">Delete</a> 
 <a href = "cmsorig.php?editid='.$id.'"> Edit</a><br/>';  //what the user sees!!!!!!!
}

?>

<form action = "cmsorig.php?<?= $_SERVER['QUERY_STRING'];//keep query string so we can see record being edited?>" method = "post">
Name: <input type = "text" name = "fullname" value="<?= $upfullname;?>"/>
<input type = "submit" name = "submit" value = "<?= $status;//either edit or add?>"/>
</form> 
<a href = "cms.php">Return to add mode</a> <!-- gets us out of edit mode!-->

