Quick and dirty webservice acces through url resons in JSON

<?php
/**   * Webservice created by Michael Schouman   *
 * 31-08-2011
 *
 * For Examples and documentation: michael@schouman.info
 *
 * TODO: Filter strange characters
 *
 */ 

// setting variables
$db = 'DATABASE';
$user = 'USERNAME';
$pass = 'PASSWORD';
$host = 'HOST';  

// date time genarator
$dateTime = new DateTime("now");  $datenow = $dateTime->format("Y-m-d H:i:s"); 

// connect to mysql database
$conn = mysql_connect($host, $user, $pass) or die('Error connecting to mysql');
mysql_select_db($db); 

// get some parameters
$action = $_REQUEST['action'];
$condition = $_REQUEST['condition'];
$message = $_REQUEST['message'];
$created = $_REQUEST['created']; 

// Array used to encode the JSON
$arr = array(); 

switch($action){ 

// Simple select
 case "select":
    $result = mysql_query("SELECT * FROM TABLE WHERE BINARY ROW = '$condition' LIMIT 1");
    $row = mysql_fetch_array($result); 

    if (empty($row)){
    $arr = array('success' => 'false');
    } else {
    $arr = array('success' => 'true');
    }
    echo json_encode($arr);
    break;
// Simple select 

// Bigger select
  case "bigselect":
    $result = mysql_query("SELECT ALL YOUR TABLES FROM TABLES WHERE BINARY ROW = '$condition'"); 

    while($art = mysql_fetch_object($result)){
      $arr[] = $art;
    }
    echo json_encode($arr);
    break;
// Bigger select

// Simple insert
  case "insert":
    $result = mysql_query("INSERT INTO TABLE(YOUR STUFF) VALUES (YOUR STUFF)");
    if (!$result) {
        $arr = array('success' => 'false');
    } else {
        $arr = array('success' => 'true');
    }
    echo json_encode($arr);
    break;
// Simple insert

}
?>

How to access

// Simple select
ws.php?action=select&condition=VARIABLE

// Bigger select
ws.php?action=bigselect&condition=VARIABLE

// Insert
ws.php?action=insert&condition=VARIABLE&message=joepie%20het%20werkt&created=2011-03-25%2005:03:53

Author: michael schouman on September 23, 2011
Category: Code snippets

Leave a Reply

Last articles