Skip to content

Instantly share code, notes, and snippets.

@lawrence254
Last active September 12, 2019 17:26
Show Gist options
  • Save lawrence254/39313589b32f2b9a399d4b49f0e3e9ea to your computer and use it in GitHub Desktop.
Save lawrence254/39313589b32f2b9a399d4b49f0e3e9ea to your computer and use it in GitHub Desktop.
Php file that recieves data from the Safaricom API and inserts select data into the DB.
<?php
//Enter your database server authentication information and name of the db you want to use
$db_server = "localhost";
$db_username = "username";
$db_password = "password";
$db_database = "dbName";
$con=mysqli_connect($db_server,$db_username,$db_password,$db_database);
$data = json_decode(file_get_contents('php://input'));
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Coloumns in the table, you can chage these but they have to match up exactly with the table
$columns = ["amount","receipt","transday","phonenumber"];
$values = array();
foreach ($data->Body->stkCallback->CallbackMetadata->Item as $item) {
if ($item->Name !== "Balance") {
$values[]=$item->Value;
}
}
$col="";
$val="";
for ($i=0; $i <count($columns) ; $i++) {
$col.=$columns[$i];
$val.="'".$values[$i]."'";
if ($i !==(count($columns)-1)) {
$col.=",";
$val.=",";
}
}
$transact="INSERT INTO transactions(".$col.")VALUES(".$val.")";
$exec = mysqli_query($con,$transact);
if($exec){
echo "Data inserted";
}else{
echo "There was an error " . mysqli_error($con);
}
mysqli_close($con);
?>
@Fbada006
Copy link

Hey. Thanks for this. I keep getting some strange errors though.

[11-Sep-2019 14:07:15 UTC] PHP Warning: Invalid argument supplied for foreach() in ....
[11-Sep-2019 14:07:15 UTC] PHP Warning: mysqli_query() expects parameter 1 to be mysqli, boolean given in...
[11-Sep-2019 14:07:15 UTC] PHP Warning: mysqli_error() expects parameter 1 to be mysqli, boolean given in.....
[11-Sep-2019 14:07:15 UTC] PHP Warning: mysqli_close() expects parameter 1 to be mysqli, boolean given in...
[12-Sep-2019 12:47:56 UTC] PHP Warning: mysqli_connect(): (HY000/1045): Access denied for user 'user '@'localhost' (using password: YES) in..

Any tips?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment