I'm trying to store a webhook response into my database table but it stores on array object, not value.
<?php
const WEBHOOK_SECRET = 'Secre_key';
function verifySignature ($body, $signature) {
$digest = hash_hmac('sha1', $rawPost, WEBHOOK_SECRET);
return $signature !== $digest ;
}
if (!verifySignature(file_get_contents('php://input'), $_SERVER['HTTP_X_TAWK_SIGNATURE'])) {
// verification failed
} else {
// verification success
$servername = "localhost";
$username = "name";
$password = "password";
$db = "twakdata";
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$json_string = file_get_contents('php://input');
$stringLen = strlen($json_string);
$array_data = json_decode($json_string, true);
$sql = 'INSERT INTO twak (message,len) VALUES ("'.$array_data.'","'.strlen($json_string).'")';
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
And the output is :
id | Message | len
1 | Array | 0
2 | Array | 0
2 | Array | 0
but I want the array value instead of the array object in the message column. Can anyone please help me.
Looking at the tawk webhook documentation you should need to change $array_data in the below line
$sql = 'INSERT INTO twak (message,len) VALUES ("'.$array_data.'","'.strlen($json_string).'")';
to
$array_data['message']['text']
This uses the text property on the message object in the webhook data to get the message text.
$array_data['message']['text']
this holds :
Name : unknown
Phone : 88776654322
Email : y#gmail.com
Question : Hello Question
these attributes, how can I grab phone number from this??
Related
I am extremely confused on how to access this data, and get it into MySQL
I have this JSON Data:
{
"serial_number": "70-b3-d5-1a-00-be",
"dateTime": "2020-08-14 20:58",
"passReport": [
{
"id": 1,
"passList": [
{
"passType": 1,
"time": "20:58:38"
}
]
}
]
}
I can get serial_number & dateTime perfectly fine, however I cannot get passType & time into my database
Here is my code for injesting:
//read the json file contents
$jsondata = file_get_contents('php://input');
//convert json object to php associative array
$data = json_decode($jsondata, true);
//mySQL creds & mySQL database & tables
$servername = "localhost";
$username = "my user";
$password = "my pass";
$dbname = "my db";
$serial_number = $data['serial_number'];
$dateTime = $data['dateTime'];
$id = $data['id'];
$passType = $data['passType'];
$time = $data['time'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//Insert into Database Tables
$sql = "INSERT INTO mytable (serial_number, dateTime, passType, time)
VALUES('$serial_number', '$dateTime', '$passType', '$time')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
I am pretty noobish at PHP, trying to learn! Appreciate any help here. I don't enough knowledge of accessing the data in the array.. Thanks in advance!
$data['passType']; makes no sense. It's clearly not on the same level of the object as serial number, for example.
You need to go down inside the hierarchy of the object. It's inside an array, and then another array.
Try
$data["passReport"][0]["passList"][0]['passType']
and
$data["passReport"][0]["passList"][0]['time']
instead.
<?php
//You can use var_dump to see the structure of decoded json, then you can access.
$jsondata = '{"serial_number":"70-b3-d5-1a-00-be","dateTime":"2020-08-14 20:58","passReport":[{"id":1,"passList":[{"passType":1,"time":"20:58:38"}]}]}';
$jdc = json_decode($jsondata,true);
var_dump($jdc);
var_dump($jdc['passReport'][0]['passList'][0]['passType']);
var_dump($jdc['passReport'][0]['passList'][0]['time']);
?>
I have YouTube video IDs stored in my database. I'm trying to output the IDs that are only invalid. I'm using get_headers / oembed which allows me to check if a video exists on YouTube. Then I am looping through the ID's. This is currently working but it's showing all YouTube IDs from my table and then adding the text "is invalid" to the ones that are invalid. I need to only display the ones that are invalid - nothing else!
I could use some help if anyone wouldn't mind. I would really appreciate it.
Code:
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT src_id FROM youtube_videos ";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo 'Video ID: '.$row["src"];
$headers = get_headers('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v='.$row["src_id"].'');
if (!strpos($headers[0], '200')) {
echo " is invalid";
} else {
echo "";
}
echo 'no results';
}
Just print the video ID if the header code is not 200?
while ($row = $result->fetch_assoc()) {
$headers = get_headers('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v='.$row["src_id"].'');
if (!strpos($headers[0], '200')) {
echo "Video ID: ".$row['src']." is invalid\n";
}
}
Might also want to look into a better way of grabbing response-headers, that thing might not be 100% accurate for all scenarios. I would suggest using something like
while ($row = $result->fetch_assoc()) {
$headers = get_headers('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v='.$row["src_id"].'');
if (substr($headers[0], 9, 3) != 200) {
echo "Video ID: ".$row['src']." is invalid\n";
}
}
I'm trying to upload a photo from an android device to host using PHP and base 64, bitmap ; but it uploads two empty images (it uploads two times) can't figure out why, any help or alternative way?
I'm uploading the photo in a register layout so I tried just inserting the photo without anything else, and I tried using another hosting service but unfortunately, nothing worked.
the name of the empty photo is inserted in the database yet in the file manager it's an empty photo
the php code;
<?php
// array for JSON response
$response = array();
$user_image= $_POST['user_image'];
$user_name= $_POST['user_name'];
$user_email= $_POST['user_email'];
$user_un= $_POST['user_un'];
$user_pass= $_POST['user_pass'];
$servername = "...";
$username = "...";
$password = "...";
$dbname = "...";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
$ra=rand(0,20000);
$rn=rand(0,40000);
$rd=rand(0,60000);
$imgname = "pl".$ra.$rn.$rd.".jpeg";
$decoding=base64_decode("$user_image");
file_put_contents("images/".$imgname,$decoding);
$sql = "INSERT INTO Users (user_name,user_email,user_un,user_pass,user_image)
VALUES ('$user_name','$user_email','$user_un','$user_pass','$imgname')";
if ($conn->query($sql) === TRUE) {
$UserId = $conn->insert_id;
$response['dishs'] = array();
$hobbie['status'] = "ok";
$hobbie['result'] = "Welcome";
// push single dishinto final response array
array_push($response['dishs'],$hobbie);
// echoing JSON response
echo json_encode($response);
} else {
// echo "Error: " . $sql . "" . $conn->error;
$response['dishs'] = array();
// failed to insert row
$hobbie['status'] = "no";
$hobbie['result'] = "Error: " . $sql . "" . $conn->error;
array_push($response['dishs'],$hobbie);
// echo no users JSON
echo json_encode($response);
}
}
$conn->close();
?>
the kotlin code
these are defined in the head of the class
"class RegisterPage :Fragment() {
var encodImg = ""
var bitmap: Bitmap? = null
......
"
sending this to the host
"... val params = HashMap<String, String>()
params["user_image"] = encodImg
...
"
the way i choose the photo from gallery and encrypt
private fun startGallery() {
val galleryIntent = Intent(Intent.ACTION_GET_CONTENT)
galleryIntent.type = "image/*"
if (galleryIntent.resolveActivity(activity!!.packageManager) != null) {
startActivityForResult(galleryIntent, 1000)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, i: Intent?) {
super.onActivityResult(requestCode, resultCode, i)
if (resultCode == Activity.RESULT_OK) {
val uri: Uri? = i!!.data
change_profile_photo.setImageURI(uri)
manageImageFromUri(i.data!!)
} else {
Toast.makeText(activity, "Error", Toast.LENGTH_LONG).show()
}
}
private fun manageImageFromUri(imageUri: Uri) {
val baos = ByteArrayOutputStream()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
Snackbar.make(view!!, "ERROR", Snackbar.LENGTH_LONG)
} else {
bitmap = MediaStore.Images.Media.getBitmap(activity?.contentResolver, imageUri)
bitmap!!.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val b = baos.toByteArray()
encodImg = Base64.encodeToString(b, Base64.DEFAULT)
}
}
}
On my server, I am attempting to find a specific string in a database table, if that string is found, I want to check to see what an integer value is in another field of the same row and UPDATE that integer if it is needed, or exit the PHP script.
The code below is only some of what I have tried. I don't see what is incorrect with the commands, and there are no error messages produced when it is ran/called.
What happens is, if the string is found, the script automatically runs the $there query.
What do I need to do to make this work correctly?
Thank you very much.
// This script checks to see if a member name sent by the page exists in the database.
//-------------------------------------------------------------
// The database section starts here.
$servername = "localhost";
$username = "manager";
$password = "********";
$dbname = "golf_ledger";
//------------------------------
// Make a connection with the server.
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check the connection.
if($conn === false){
die("ERROR: Couldn't connect. " . mysqli_connect_error());
}
else {
echo "The connection worked."."<br>"."<br>";
}
//------------------------------------------------------------------
// This is the test string to be searched for.
$memName = "Richardson";
//----------------------------------------
// Populate $result with the search query.
// Database name Table name
$result = mysqli_query($conn,"SELECT * FROM `golf_ledger`.`member_table` WHERE `member_table`.`name` = '$memName'");
if(mysqli_num_rows($result) == 0) {
echo "Sorry, the name was not found";
die();
}
//----------------------------------------
// Something is wrong with this one, possibly.
$there = mysqli_query($conn,"SELECT * FROM `golf_ledger`.`member_table` WHERE `member_table`.`name` = '$memName' AND `member_table`.`pay_Status` = 1");
// "if ($there)" is the same as "if ($there == true)" in PHP.
if ($there == true) {
echo "The name has been found, and they have paid.";
die();
}
//----------------------------------------
$notThere = mysqli_query($conn,"SELECT * FROM `golf_ledger`.`member_table` WHERE `member_table`.`name` = '$memName' AND `member_table`.`pay_Status` = 0");
if ($notThere == true) {
mysqli_query($conn,"UPDATE `golf_ledger`.`member_table` SET `pay_Status` = 1 WHERE `member_table`.`name` = '$memName'");
echo "The name has been found, they have NOT paid, but the status has been updated.";
die();
}
Instead of this code:
if ($there == true) {
echo "The name has been found, and they have paid.";
die();
}
try that:
// Check if found any records
if (mysqli_num_rows($there) > 0) {
echo "The name has been found, and they have paid.";
die();
}
XML Codes
I have got a item list xml file for a game server, and I need to insert item names, id's and type of the item into a mysql server. I have provided 4 examples of situations, first has isstaffitem="true", second has iscashitem="true" third iscashitem="false" and fourth has nothing regarding item type. Now what I need is to read the id="string", name="string" and type of the item and insert into database. If it's staff item, set type as staff, if cash item set type to cash and set regular if something else.
How can I do that php ? I am trying with $xml = simplexml_load_string($_POST['zitem']); but can't get it work..
Here's some example code. I created a simple HTML-form, with a textarea to input the XML-code. After hitting "Submit", the PHP-script is triggered (server method = post). Connect to your database (example from w3schools). Parse the XML-string as a DomDocument (gives you more options then simple_xml). Insert each item in your xml into MySQL.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Make connection to database first
// example from http://www.w3schools.com/php/php_mysql_insert.asp
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Use DomDocument (more options / flexibility)
$doc = new DOMDocument();
$doc->loadXML($_POST['zitem']);
$items = $dom->getElementsByTagName('ITEM');
foreach ($items as $item) {
// The attributed in the XML item "ITEM", can be retrieved by using $item->getAttribute('nameofattribute')
$id = $item->getAttribute('id');
$name = $item->getAttribute('name');
$mesh_name = $item->getAttribute('mesh_name');
// Some logic, see for yourself.
$cashitem = false;
if ($item->getAttribute('iscashitem') == true) {
$cashitem = true;
}
$staffitem = false;
if ($item->getAttribute('isstaffitem') == true) {
$staffitem = true;
}
// Insert the item from XML into MySQL-table
$sql = "
INSERT INTO Items
(id, name, mesh_name, cashitem, staffitem)
VALUES (
'" . $mysqli->real_escape_string($id) . "',
'" . $mysqli->real_escape_string($name) . "',
'" . $mysqli->real_escape_string($mesh_name) . "',
'somevaluehere',
'somevaluehere'
)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
}
?>
<form method="post">
<textarea name="zitem"></textarea>
<input type="submit" value="Submit your XML file" />
</form>
Good luck!