Skip to content

Instantly share code, notes, and snippets.

@ttristan
Last active March 23, 2018 08:19
Show Gist options
  • Save ttristan/695d22c4632c7c0af793a9f34db65006 to your computer and use it in GitHub Desktop.
Save ttristan/695d22c4632c7c0af793a9f34db65006 to your computer and use it in GitHub Desktop.
<?php
// open connection
$con = mysqli_connect('host', 'user', 'pass', 'db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
// get post data
$data = json_decode(file_get_contents('php://input'), true);
/*
* SELECT
*/
$stmt = $con->prepare("SELECT * FROM x WHERE x = ? AND y = ? AND z = ? AND a IS NULL LIMIT ?");
// bind params
$stmt->bind_param("sisi", $data["string"], $data["int"], $data["string"], $data["int"]);
// execute
$stmt->execute();
// catch error
printf($stmt->error);
// bind & store results
$stmt->bind_result($vars);
$stmt->store_result();
$resultSet = array(); // init result set array
if ($stmt->num_rows === 1) { // loop over result, here only 1 row should be given
while ($stmt->fetch()) {
$row = array( // current row as array, set key => value
"key" => $vars,
"key" => $vars,
);
array_push($resultSet, $row); // add row to resultset
}
echo json_encode($resultSet); // encode to json
}
else echo "false"; // catch
/*
* Update
*/
$stmt = $con->prepare("UPDATE x SET y = ? WHERE z = ?");
// bind params
echo $stmt->affected_rows;
// close stmt & DB connection
$stmt->close();
$con->close();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment