You are on page 1of 2

<?

php
// Requires
require("./Connection.php");

// Variables
$db = new Connection();
$connection = $db->create_connection();
$request_method = $_SERVER["REQUEST_METHOD"];
$inProduction = FALSE; // Set to TRUE if in production.
header( 'Content-Type: application/json' );

// Helper functions
function output( $data ) {
echo json_encode( $data );
}
function sanitize_numbers( $input ) {
$maxLength = 255;
if ( ( !$inProduction ) && ( strlen( $input ) > $maxLength ) )
output( [ 'Error' => 'Input lenght is greater than 255!' ] );
if ( ( !$inProduction ) && ( preg_match( '/[^0-9]/', $input ) ) )
output( [ 'Error' => 'Input contains illegal characters!' ] );
return substr( preg_replace( '/[^0-9]/', '', $input ), 0, $maxLength );
}

// API functions
function get_news( $connection ) {
try {
$news = $connection->prepare( 'SELECT id, title, date, text FROM news' );
$news->execute();
$result = $news->FetchAll( PDO::FETCH_ASSOC );
foreach( $result as $all ){
output( $all );
}
} catch ( PDOException $e ) {
if ( !$inProduction ) {
throw new pdoDbException( $e );
} else {
output( [ 'Error occured' => 'Please try again!' ] );
}
}
}

function get_news_by_id( $connection, $id ) {
try {
$news = $connection->prepare( 'SELECT id, title, date, text FROM news WHERE
id= '. sanitize_numbers( $id ) );
$news->execute();
$result = $news->FetchAll( PDO::FETCH_ASSOC );
if ( empty ($result) ) {
return output( [ 'Error' => 'No results.' ] );
}
foreach( $result as $all ){
output( $all );
}
} catch ( PDOException $e ) {
if ( !$inProduction ) {
throw new pdoDbException( $e );
} else {
output( [ 'Error occured' => 'Please try again!' ] );

}. text) VALUES(:title. "text" => "sexy")). $benom = post_news_by_id( $connection ) ?> . } $result = $news. date ='' '" . output($result). { $title = $_POST['title']. } $result = $news. "'. } } } function post_news_by_id( $connection ) { try { if (isset($_POST['id']). } } function insert_news_by_id ($connection) { try { { $news = $connection->prepare("INSERT INTO news (title. if ($result != 0) { $result = array('success' => 1). $text = $_POST['text']. :date. :text)"). $news->execute(). "' WHERE id ='' " . "date" => "2018". $date . text ='' '" . } else { output(['Error occured' => 'Please try again!']). $_GET['id']). $text . $title . $news = $connection->prepare("UPDATE news SET title = '" . }. date. output($result). } catch (PDOException $e) { if (!$inProduction) { throw new pdoDbException($e). "'. $date = $_POST['date']. phpinfo() $id = $_GET['id']. if ($result != 0) { $result = array('success' => 1). } } } // Testing // $domat = get_news( $connection ). $news->execute(array("title" => "Bob".