Showing results for 
Search instead for 
Did you mean: 

How would I insert and update my MySQL database using the this RestApi?



Being fairly new to Restful Api, I am in doubt as to how I would retrieve and update my MySQL database using the following PHP Restful API.



// get the HTTP method, path and body of the request
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);

// connect to the mysql database
$link = mysqli_connect('localhost', 'user', 'pass', 'dbname');

// retrieve the table and key from the path
$table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
$key = array_shift($request)+0;

// escape the columns and values from the input object
$columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
$values = array_map(function ($value) use ($link) {
if ($value===null) return null;
return mysqli_real_escape_string($link,(string)$value);

// build the SET part of the SQL command
$set = '';
for ($i=0;$i<count($columns);$i++) {

// create SQL based on HTTP method
switch ($method) {
case 'GET':
$sql = "select * from `$table`".($key?" WHERE id=$key":''); break;
case 'PUT':
$sql = "update `$table` set $set where id=$key"; break;
case 'POST':
$sql = "insert into `$table` set $set"; break;
case 'DELETE':
$sql = "delete `$table` where id=$key"; break;

// excecute SQL statement
$result = mysqli_query($link,$sql);

// die if SQL statement failed
if (!$result) {

// print results, insert id or affected row count
if ($method == 'GET') {
if (!$key) echo '[';
for ($i=0;$i<mysqli_num_rows($result);$i++) {
echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
if (!$key) echo ']';
} elseif ($method == 'POST') {
echo mysqli_insert_id($link);
} else {
echo mysqli_affected_rows($link);

// close mysql connection


There are multiple protocols that you can choose from, to set up the connection with your MySQL servers. These are as follows:

  • jdbc:mysql: This protocol helps set up ordinary & JDBC failover connections.
  • jdbc:mysql:loadbalance: This protocol houses support for load balancing.
  • jdbc:mysql:replication: This protocol helps set up JDBC-based replication connections.

You can further provide one or multiple hostnames in the “host parameter”, along with port numbers to specify host-specific properties. For example, you can create a connection URL as follows: