diff --git a/index.php b/index.php index a45c8be..0a0c190 100644 --- a/index.php +++ b/index.php @@ -3,24 +3,32 @@ require_once('persistence.php'); $db = createDB(); ?> - + Guestbook - + '); - foreach($msg as $key => $value) { - echo(""); - } - echo(''); + //storeMessage($db, 'Hola Dendy'); + if(deleteMessage($db, 1)) { + echo('Success'); } + else { + echo('Failure'); + } + $test = getMessages($db); + foreach($test as $msg) { + echo('
'); + foreach($msg as $key => $value) { + echo('
'); + echo("$key: $value"); + echo('
'); + } + echo('
'); + echo('
'); + } ?> -
$key: $value
diff --git a/persistence.php b/persistence.php index d0fd22d..8eda79b 100644 --- a/persistence.php +++ b/persistence.php @@ -3,7 +3,6 @@ function createDB($db_name = 'guestbook.db'): SQLite3 { // Can't create table if it already exists $exists = file_exists($db_name); - $db = new SQLite3($db_name); if(!$exists) { @@ -43,7 +42,6 @@ function getMessages(SQLite3 $db, array $filter = [], int $limit = 25) { // Prepare statement $query = 'SELECT * FROM message' . $append_string; //var_dump($query); - $statement = $db->prepare($query); foreach($filter as $key => $value) { @@ -51,7 +49,6 @@ function getMessages(SQLite3 $db, array $filter = [], int $limit = 25) { } $result = $statement->execute(); - $notnull = true; $ret = []; while($notnull) { @@ -67,7 +64,9 @@ function getMessages(SQLite3 $db, array $filter = [], int $limit = 25) { } function storeMessage(SQLite3 $db, string $content, ?int $user_id = null) { - $query = 'INSERT INTO message(id_user, content, date) VALUES (:id_user, :content, :date)'; + $query = 'INSERT INTO message(id_user, content, date) + VALUES (:id_user, :content, :date)'; + $date = (new DateTime('now'))->getTimestamp(); $statement = $db->prepare($query); $statement->bindParam(':id_user', $user_id); @@ -75,3 +74,17 @@ function storeMessage(SQLite3 $db, string $content, ?int $user_id = null) { $statement->bindParam(':date', $date); $statement->execute(); } + +function deleteMessage(SQLite3 $db, int $message_id) : int { + $query = 'DELETE FROM message + WHERE id_msg = :id_msg'; + + $statement = $db->prepare($query); + $statement->bindParam(':id_msg', $message_id); + $result = $statement->execute(); + if ($result === false) { + return -1; + } + // Number of changed rows + return $db->changes(); +}