I've seen many others questions and answers on the Web, but I haven't found the solution to my issue.
Basically, I've create an API page. If I use a API tester (such as apitester.com) it works correctly.
Instead, when I do POST request from Volley (Android-Kotlin) it doens't work.
It looks like params are empty.
I can't understand the problem.
PHP Code:
include_once($_SERVER['DOCUMENT_ROOT'] . "/include/variables.php");
global $localhost_db, $username_db, $password_db, $database_api;
header("Content-Type:application/json");
if ($c = new mysqli($localhost_db, $username_db, $password_db, $database_api)) {
$c->set_charset("utf8");
//POST request -> insert a new data to database
$data = json_decode(file_get_contents('php://input'), true);
$condition = isset($data["logged"]) && ($data["logged"] == 0 || $data["logged"] == 1) && isset($data["username"]) && isset($data["language"]);
if ($condition) {
$year = date('Y');
$month = date("m");
$day = date("d");
$sql = "SELECT `date` FROM statistics WHERE `username`='" . $data["username"] . "' AND YEAR(`date`)=" . $year . " AND MONTH(`date`)=" . $month . " AND DAY(`date`)=" . $day;
if ($r = $c->query($sql)) {
if ($r->num_rows == 0) {
$sql = "INSERT INTO statistics(`id`, `date`, `logged`, `username`, `language`) VALUES(NULL,'" . date("Y-m-d H:i:s") . "', '" . $data["logged"] . "', '" . $data["username"] . "', '" . $data["language"] . "')";
if ($r = $c->query($sql)) {
response(200, "OK", "Record inserted correctly");
} else {
response(500, "Error", "Can't insert record on database");
}
} else {
response(400, "Error", "Record has already inserted today");
}
} else {
response(400, "Error", "Something was wrong in POST request (1)");
}
} else {
response(400, "Error", "Something was wrong in POST request (2). Received data> logged: " . $data["logged"] . ", language: " . $data["language"] . ", username: " . $data["username"]);
}
} else {
echo "Failed to connect to the database.";
response(500, "Error", "Can't connect to the database");
}
function response($response_code, $response_status, $response_description)
{
$response['code'] = $response_code;
$response['status'] = $response_status;
$response['description'] = $response_description;
$json_response = json_encode($response);
echo $json_response;
}
?>
instead the Android Kotlin code:
var params = JSONObject()
params.put("username", username)
params.put("logged", logged)
params.put("language", language)
val que = Volley.newRequestQueue(this)
val req = object : JsonObjectRequest(Request.Method.POST, url_statistics, params,
Response.Listener {
val jsonResult = it.toString()
var jsonResultArray = arrayOf(jsonResult, "")
println(jsonResult)
val jsonObj = JSONObject(
jsonResultArray[0].substring(
jsonResultArray[0].indexOf("{"),
jsonResultArray[0].lastIndexOf("}") + 1
)
)
if (jsonObj.getString("code")
.toInt() == 200
) {//Successful}
else {//Error}
}, Response.ErrorListener {
//Error
}
){}
que.add(req)
do this:
$username = $_POST['username']
instead of:
$data = json_decode(file_get_contents('php://input'), true);
Related
I am trying to get in a Google spreadsheet via the PHP API Client, but I am getting a 404->You need permission. The file has been given edit permissions to my user, which is the user I used to set up the JSON credentials via the Google Developers Console. What am I missing?
Here is my code :
$this->client = new Google_Client();
$this->client->setApplicationName('BreezingForms Google Drive Spreadsheets');
$this->client->addScope(array('https://spreadsheets.google.com/feeds'));
// testing:
// 197794184197-bt2q9knrdu1i54vgladd97ob196k4c6s.apps.googleusercontent.com
// dImciIWj3WNOrIcYRbu9MFeA
if (isset($_POST['gdata_custom_client_id']) && trim($_POST['gdata_custom_client_id']) != '' && trim($_POST['gdata_custom_client_secret']) != '') {
$this->client->setClientId(trim($_POST['gdata_custom_client_id']));
$this->client->setClientSecret(trim($_POST['gdata_custom_client_secret']));
$db->setQuery("Update #__breezingforms_addons_gdata Set custom_client_id = " . $db->quote(trim($_POST['gdata_custom_client_id'])) . ", custom_client_secret = " . $db->quote(trim($_POST['gdata_custom_client_secret'])) . " Where form_id = " . intval($_REQUEST['form']));
$db->execute();
} else {
$form_id = -1;
if(JRequest::getInt('ff_form',-1) > 0){
$form_id = JRequest::getInt('ff_form',-1);
}else if(isset($_REQUEST['form'])){
$form_id = intval($_REQUEST['form']);
}
$db->setQuery("Select * From #__breezingforms_addons_gdata Where form_id = " . $db->quote($form_id));
$client = $db->loadObject();
if ($client) {
$this->client->setClientId($client->custom_client_id);
$this->client->setClientSecret($client->custom_client_secret);
}
}
$this->client->setApprovalPrompt('auto');
$this->client->setPrompt('consent');
$this->client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$this->client->setAccessType('offline');
}
function onPropertiesDisplay($form_id, $tabs){
if(!$form_id) return '';
$error = '';
$db = JFactory::getDBO();
$db->setQuery("Select `title`,`name`,`id` From #__facileforms_elements Where form = " . intval($form_id) . " And `title` Not In ('bfFakeTitle','bfFakeTitle2','bfFakeTitle3','bfFakeTitle4','bfFakeTitle5') And `type` Not In ('','UNKNOWN') Order By ordering");
$breezingforms_fields = $db->loadObjectList();
$db->setQuery("Select `enabled`, `username`, `password`, `worksheet_id`, `spreadsheet_id`, `fields`, `meta`, `debug` From #__breezingforms_addons_gdata Where form_id = " . intval($form_id));
$gdata = $db->loadObject();
if( $gdata === null ){
$gdata = new stdClass();
$gdata->username = '';
$gdata->password = '';
$gdata->enabled = 0;
$gdata->worksheet_id = '';
$gdata->spreadsheet_id = '';
$gdata->fields = '';
$gdata->meta = '';
$gdata->debug = 0;
}
$gdata->fields = explode('/,/', $gdata->fields);
$gdata->meta = explode('/,/', $gdata->meta);
$gdata_spreadsheets = array();
$gdata_worksheets = array();
$gdata_columns = array();
//if( $gdata->enabled == 1 ){
try{
$spreadsheetFeed = null;
$auth_url = '';
$db->setQuery("Select password From #__breezingforms_addons_gdata Where form_id = " . intval($form_id));
$accessToken = $db->loadResult();
// $accessToken='{"access_token":"ya29.a0ARrdaM--_ZKuuOfK3CyRsAubHXYgGlwMhLfg9x10fLbYhOq0Polqela1GjGYjhBO9Fi0v7LKuDauV4qA-uFLCilun0_NuQDuEFHjYb9iX0rcOjS6YWMDTHfe2UsyxJkyvlULrMIV7sh4_-_-vORj0kh6sw7o","expires_in":3599,"refresh_token":"1\/\/09aQ4SG_STBzBCgYIARAAGAkSNwF-L9Ir9FDHRmbwiLoCXglVSksa1tfyes6AdQedbTx2dqZKGh-ZTMT-M2i665x18NzT1luWu1Q","scope":"https:\/\/www.googleapis.com\/auth\/spreadsheets","token_type":"Bearer","created":1635842294}';
if(!$accessToken){
$auth_url = $this->client->createAuthUrl();
} else {
try{
$this->client->setAccessToken($accessToken);
$token = json_decode($accessToken);
if ($this->client->isAccessTokenExpired()) {
$this->client->refreshToken($token->refresh_token);
$tok = json_encode($this->client->getAccessToken());
$token = json_decode($tok);
$db->setQuery("Update #__breezingforms_addons_gdata set password = " . $db->quote($tok) . " Where form_id = " . intval($form_id));
$db->execute();
}
$serviceRequest = new DefaultServiceRequest($token->access_token, $token->token_type);
ServiceRequestFactory::setInstance($serviceRequest);
$spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
$spreadsheetFeed = $spreadsheetService->getSpreadsheets();
}catch(Exception $ee){
//$accessToken = null;
//$auth_url = $this->client->createAuthUrl();
$error=$ee->getMessage();
}
}
if($spreadsheetFeed !== null){
foreach($spreadsheetFeed As $sheet){
$gdata_spreadsheets[$sheet->getId()] = $sheet->getTitle();
}
}
if($gdata->spreadsheet_id != '' && isset( $gdata_spreadsheets[$gdata->spreadsheet_id] ) && $spreadsheetFeed !== null){
$spreadsheet = $spreadsheetFeed->getByTitle($gdata_spreadsheets[$gdata->spreadsheet_id]);
$worksheetFeed = $spreadsheet->getWorksheets();
foreach ( $worksheetFeed as $sheet ){
$gdata_worksheets[$sheet->getId()] = $sheet->getTitle();
}
if($gdata->worksheet_id != '' && isset( $gdata_worksheets[$gdata->worksheet_id] )){
$worksheet = $worksheetFeed->getByTitle($gdata_worksheets[$gdata->worksheet_id]);
$cellFeed = $worksheet->getCellFeed();
foreach($cellFeed->getEntries() as $cellEntry) {
$row = $cellEntry->getRow();
$col = $cellEntry->getColumn();
if( $row > 1 ){
break;
}
$gdata_columns[] = $cellFeed->getCell($row, $col)->getContent();
}
}
}
} catch(Exception $e){
$error = $e->getMessage();
}
//}
ob_start();
$version = new JVersion();
if(version_compare($version->getShortVersion(), '1.6', '<')){
require_once JPATH_SITE . DS . 'plugins' . DS . 'breezingforms_addons' . DS . 'breezingforms_addons_gdata_tmpl' . DS . 'properties.php';
}else{
require_once JPATH_SITE . DS . 'plugins' . DS . 'breezingforms_addons' . DS . 'gdata' . DS . 'breezingforms_addons_gdata_tmpl' . DS . 'properties.php';
}
$c = ob_get_contents();
ob_end_clean();
return $c;
}
function onPropertiesSave($form_id){
if(!$form_id) return '';
$accessToken = '';
$reset_accessToken = false;
if(isset($_POST['gdata_code']) && $_POST['gdata_code'] != ''){
$accessToken =json_encode($this->client->authenticate($_POST['gdata_code']));
}
if(isset($_POST['gdata_reset'])){
$reset_accessToken = true;
$accessToken = '';
}
if(isset($_POST['gdata_fields']) && is_array($_POST['gdata_fields'])){
$_POST['gdata_fields'] = implode('/,/', $_POST['gdata_fields']);
}else{
$_POST['gdata_fields'] = '';
}
if(isset($_POST['gdata_meta']) && is_array($_POST['gdata_meta'])){
$_POST['gdata_meta'] = implode('/,/', $_POST['gdata_meta']);
}else{
$_POST['gdata_meta'] = '';
}
$db = JFactory::getDBO();
$db->setQuery("Select form_id From #__breezingforms_addons_gdata Where form_id = " . intval($form_id));
$exists = $db->loadResult();
if(!$exists){
$db->setQuery("Insert Into #__breezingforms_addons_gdata (
`form_id`, `enabled`,`password`,`spreadsheet_id`,`worksheet_id`,`fields`,`meta`) Values
( ".intval($form_id).",
".JRequest::getInt('gdata_enabled', 0).",
".($accessToken ? $db->quote($accessToken).',' : '"",')."
".$db->quote(hexToStr(JRequest::getVar('gdata_spreadsheet_id', "''"))).",
".$db->quote(hexToStr(JRequest::getVar('gdata_worksheet_id', "''"))).",
".$db->quote($_POST['gdata_fields']).",
".$db->quote($_POST['gdata_meta'])."
)");
$db->query();
}
else {
//$token1=json_encode(array("username" => "text",
//"password" => "text"));
$gspid = $reset_accessToken ? "''" : hexToStr(JRequest::getVar('gdata_spreadsheet_id', "''"));
$wid = $reset_accessToken ? "''" : hexToStr(JRequest::getVar('gdata_worksheet_id', "''"));
$db->setQuery("Update #__breezingforms_addons_gdata Set
`enabled` = ".JRequest::getInt('gdata_enabled', 0).",
".($accessToken || $reset_accessToken ? "`password` = " . $db->quote($accessToken).',' : '')."
`spreadsheet_id` = ".$db->quote(trim($gspid) == '' ? "''" : $gspid).",
`worksheet_id` = ".$db->quote(trim($wid) == '' ? "''" : $wid).",
`fields` = ".$db->quote($_POST['gdata_fields']).",
`meta` = ".$db->quote($_POST['gdata_meta'])."
".($reset_accessToken ? ",`custom_client_id` = " . $db->quote("34263101371-4rcre0p6r9ehuhoat1d6ls8u84etuanp.apps.googleusercontent.com").', `custom_client_secret` = ' . $db->quote("IDq59sdLo6wC81KCUweDKVf2") : '')."
Where form_id = " . intval($form_id) . "
");
$db->query();
}
I give permission app to access on my Goole account, then I get auth token back from the Google account, but then I got "you to need permission"!?
Any idea?
The error you are encountering comes from the fact that the https://spreadsheets.google.com/feeds scope you are using is an invalid one.
The list of authorized scopes for Sheets API is the following one:
https://www.googleapis.com/auth/drive which allows you to see, edit, create, and delete all of your Google Drive files;
https://www.googleapis.com/auth/drive.file which allows you to view and manage Google Drive files and folders that you have opened or created with this app;
https://www.googleapis.com/auth/drive.readonly which allows you to see and download all your Google Drive files;
https://www.googleapis.com/auth/spreadsheets which allows you to see, edit, create, and delete your spreadsheets in Google Drive;
https://www.googleapis.com/auth/spreadsheets.readonly which allows you to view your Google Spreadsheets.
Therefore, depending on the exact actions you want to allow your users to make, you will have to choose one of the scopes from the list above. Moreover, make sure to delete the token.json file if you end up modifying the scopes.
Reference
Sheets API Authorize Requests.
Alert line code is not working as I want to show alert on particular condition but code die after that and alert is also not showing. please tell the solution for this.
case "NEW_REC_INSTANCE_PRIPB":
if (!empty($_REQUEST['PRIADCTG']) && !empty($_REQUEST['SEC_CD']) && !empty($_REQUEST['MATCODE']) && empty($_REQUEST['CLIENT_ADD'])) {
$data = array();
$qRSet = $objComm->GET_QUICK_RESULT("SELECT NVL (address_required, 'N') ADDE_REQ FROM " . $_SESSION['DB_USER'] . ".ad_ccpctg WHERE priadctg = '" . $_REQUEST['PRIADCTG'] . "' AND priccpctg = '" . $_REQUEST['SEC_CD'] . "' AND secccpctg = '" . $_REQUEST['MATCODE'] . "'
AND status = 'Y'", 1);
IF ($qRSet['ADDE_REQ'] == 'Y') {
echo '<script type="text/javascript">alert("Client address is required to enter! please check");</script>';
if (!file_put_contents($_SERVER["DOCUMENT_ROOT"] . '/DS/ccpentry_new/AS_PHP/uploadfile/DAA.txt', $qRSet['ADDE_REQ'])) {
echo 'unable to write';
die;
}
$data['ADD_REQ'] = $qRSet['ADDE_REQ'];
} else {
$data['ADD_REQ'] = $qRSet['ADDE_REQ'];
}
}
if ($_REQUEST['actype'] == "FIRST_NEW_REC") {
$newRecInsDet = $objGbl->SET_PUBL_NEWREC_INSTANCE($_REQUEST, "FY");
} else if ($_REQUEST['actype'] == "NEW_REC") {
$newRecInsDet = $objGbl->SET_PUBL_NEWREC_INSTANCE($_REQUEST, "Y");
} else {
$newRecInsDet = $objGbl->savePubData($_REQUEST, '', "", 1, $_REQUEST['INSNUM']);
}
echo json_encode($newRecInsDet);
exit;
break;
case "NEW_REC_INSTANCE_PRIPB":
$new_array = array();
if (!empty($_REQUEST['PRIADCTG']) && !empty($_REQUEST['SEC_CD']) && !empty($_REQUEST['MATCODE']) && empty($_REQUEST['CLIENT_ADD'])) {
$data = array();
$qRSet = $objComm->GET_QUICK_RESULT("SELECT NVL (address_required, 'N') ADDE_REQ FROM " . $_SESSION['DB_USER'] . ".ad_ccpctg WHERE priadctg = '" . $_REQUEST['PRIADCTG'] . "' AND priccpctg = '" . $_REQUEST['SEC_CD'] . "' AND secccpctg = '" . $_REQUEST['MATCODE'] . "' AND status = 'Y'", 1);
IF ($qRSet['ADDE_REQ'] == 'Y') {
$new_array['success'] = false;
$new_array['error'] = 'Client address is required to enter! please check';
if (!file_put_contents($_SERVER["DOCUMENT_ROOT"] . '/DS/ccpentry_new/AS_PHP/uploadfile/DAA.txt', $qRSet['ADDE_REQ'])) {
echo 'unable to write';
die;
}
$data['ADD_REQ'] = $qRSet['ADDE_REQ'];
} else {
$data['ADD_REQ'] = $qRSet['ADDE_REQ'];
}
}
if ($_REQUEST['actype'] == "FIRST_NEW_REC") {
$new_array['success'] = true;
$new_array['data'] = $objGbl->SET_PUBL_NEWREC_INSTANCE($_REQUEST, "FY");
} else if ($_REQUEST['actype'] == "NEW_REC") {
$new_array['success'] = true;
$new_array['data'] =$objGbl->SET_PUBL_NEWREC_INSTANCE($_REQUEST, "Y");
} else {
$new_array['success'] = true;
$new_array['data'] = $objGbl->savePubData($_REQUEST, '', "", 1, $_REQUEST['INSNUM'])
}
echo json_encode($new_array);
exit;
break;
Good day,
I'm trying to run a stored procedure on a mysql server by calling a php function.
I have used a lot of 'echo' lines to check where the problem could be but it seems that the problem occurs at the very end of my process when I try to send the data (namely '$idComponent' and '$data_get'). However, even if I set fixed values (50 for the id component and 50 for the value), the stored procedure does not send data to my table, either.
Before annoying you, I have been googling for a while, but now I am quite lost as I don't really know now where to look at.
<?php
/*
php_update_survey_local.php
*****************************************************************************************
* This script updates the value of the components in the table tbl_domotique_components
* It calls the stored procedure 'sp_tbl_eedomus_local_surveys_insert'
*****************************************************************************************
Version 1.00, 08.06.2017, Initial version of the script
*/
mainProcess();
function mainProcess()
{
$stringLen = 0;
$stringValue1 = "";
$stringValue2 = "";
$mavalue = "vide";
$data_get = -9999.999;
$eedomus_api_link = "https://api.eedomus.com/get?api_user=user&api_secret=data&action=periph.caract&periph_id=";
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo "Link : " . $actual_link . "<br>" ;
$stringLen = strlen($actual_link);
echo "Length : " . $stringLen;
$stringPos1 = strpos($actual_link, 'Param1');
$stringPos2 = strpos($actual_link, '&', $stringPos1);
$stringValue1 = substr($actual_link, $stringPos1+7, $stringPos2 - $stringPos1 - 7);
echo "Pos : " . $stringPos2;
echo "Extracted string 1 : #" . $stringValue1 . "#<br>";
$stringPos1 = strpos($actual_link, 'Param2', $stringPos2);
$stringValue2 = substr($actual_link, $stringPos1+7, $stringLen - $stringPos1 - 7);
echo "Pos : " . $stringPos1;
echo "Extracted string 2 : #" . $stringValue2 . "#<br>";
$ServerIP = "myIPAddress";
$sqlUser = "domoos";
$sqlDatabase = "domoos_test_db";
$pw = "toto";
$file_input_1 = "../auto/file/update_data_" . $stringValue1. ".txt" ;
$eedomus_component_path_full_1 = $eedomus_api_link . $stringValue1;
getFile($file_input_1, $eedomus_component_path_full_1);
$data_get = extractData($file_input_1, $eedomus_component_path_full_1);
// Connect
$mysqli = new mysqli($ServerIP, $sqlUser, $pw, $sqlDatabase);
if(!$mysqli) {
header('Location: error.php?error=DbConnectionFailure');
die();
}
$idComponent = intval($stringValue1);
echo "ID COMP = " . $idComponent;
echo "VALUE = " . $data_get;
// Prepare IN parameters
// $mysqli->query("SET #p_Id_Component = '" . $idComponent . "'");
// $mysqli->query("SET #p_Value = '" . $data_get . "'");
$mysqli->query("SET #p_Id_Component = 50");
$mysqli->query("SET #p_Value = 50");
if(!$mysqli->query("CALL sp_tbl_eedomus_local_surveys_insert (#p_Id_Component, #p_Value)"))
{
echo "OK";
if($mysqli) $mysqli->close(); // Close DB connection
//header('Location: error.php?error=QueryFailure');
die();
}
if($mysqli) $mysqli->close(); // Close DB connection
}
function getFile($file_input, $eedomus_component_path_full_1)
{
file_put_contents($file_input, fopen($eedomus_component_path_full_1, 'r'));
sleep(1);
}
function extractData($file_input, $eedomus_component_path_full_1)
{
// Fonction pour mettre à jour la température dans domoos
if ( 0 == filesize( $file_input ) )
{
// file is empty - the treatment is stopped here
// writeToLog($log_file_name, "[Failure] Empty file detected (" . $file_input . ")");
}
else
{
echo "fichier PAS vide";
$consolidated = "";
$lines = file($file_input);
// writeToLog($log_file_name, "[Success] Eedomus component data collected (" . $eedomus_component_path_full_1 . " -> " . $file_input . ")");
foreach($lines as $line)
{
$consolidated = $consolidated . $line;
}
// Initial values
$Temperature_Float = 0;
$Pos1 = 0;
$Pos2 = 0;
$Pos3 = 0;
$Pos4 = 0;
$Json_Input = $consolidated;
$Pos1 = strpos($Json_Input, "\"last_value\"", 0);
$Pos2 = strpos($Json_Input, ":", $Pos1+1);
$Pos3 = strpos($Json_Input, "\"", $Pos2+1);
$Pos4 = strpos($Json_Input, "\"", $Pos3+1);
$Temperature_String = substr($Json_Input, $Pos3+1, $Pos4-$Pos3-1);
$Temperature_Float = floatval($Temperature_String);
echo "Coucou. " . "A la maison, il fait maintenant : <b>" . round($Temperature_Float,0) . "°C</b>";
echo "<br>Contrôle : ";
echo "<br>Position 1 : " . $Pos1;
echo "<br>Position 2 : " . $Pos2;
echo "<br>Position 3 : " . $Pos3;
echo "<br>Position 4 : " . $Pos4;
echo "<br>Chaîne extraîte : " . $Temperature_String;
// return round($Temperature_Float,0);
return $Temperature_Float;
}
}
?>
If it's useful here is what my stored procedure 'sp_tbl_eedomus_local_surveys_insert' does :
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `sp_tbl_eedomus_local_surveys_insert`(IN `p_Id_Component` INT, IN `p_Value` FLOAT, OUT `p_last_id` INT)
NO SQL
BEGIN
INSERT INTO tbl_eedomus_local_surveys
(
eedomus_id,
eedomus_value
)
VALUES
(
p_Id_Component,
p_Value
);
SET
p_last_id = LAST_INSERT_ID();
END$$
DELIMITER ;
Any idea of what am I doing wrong here? Many thanks for your time and for reading me.
Guys I'm working on the developing an app and I have a very strange problem. I have a database and a web service, I wrote a number of procedures and functions in the database and all well work within the environment MySql, but when I use from URL Request, not show true query (Always run else condition and show me record 'xxxx' that record for response when I understand send data from isn't true and invalid and not show me blank json like '[ ]'), almost all things test, like character set,... (all things that been comments) please help me in the below you're showing my code in the web service and Mysql: php side and Web service:
<?php
if (isset($_REQUEST['action'])) {
$action = $_REQUEST['action'];
} else {
echo "invalid Data";
exit;
}
switch ($action) {
case "getRecord" :
getRecord($_REQUEST['ID'], $_REQUEST['email'], $_REQUEST['mobile']);
break;
.
.
.
.
default:
echo "Your action select is not true!";
}
FUNCTION getRecord($ID, $Email, $Mobile)
{
$con = mysqli_connect("localhost", "root", "root", "myDB");
/*mb_detect_encoding($ID,"ascii");
mb_detect_encoding($Mobile,"ascii");
mb_detect_encoding($Email,"ascii");*/
mb_convert_encoding($ID, 'ascii');
mb_convert_encoding($Email, 'ascii');
mb_convert_encoding($Mobile, 'ascii');
if (mb_check_encoding($ID, "UTF-8")) {
echo "UTF-8 Yes!!!" . PHP_EOL;
}
if (mb_check_encoding($Email, "UTF-8")) {
echo "UTF-8 Yes!!!" . PHP_EOL;
}
if (mb_check_encoding($Mobile, "UTF-8")) {
echo "UTF-8 Yes!!!" . PHP_EOL;
}
if (mb_check_encoding($ID, "ascii")) {
echo "ascii Yes!!!" . PHP_EOL;
}
if (mb_check_encoding($Email, "ascii")) {
echo "ascii Yes!!!" . PHP_EOL;
}
if (mb_check_encoding($Mobile, "ascii")) {
echo "ascii Yes!!!" . PHP_EOL;
}
if (is_int($ID)) {
echo "ID is Integer Yes!!!" . PHP_EOL;
} else {
echo "ID is not Integer!!!" . PHP_EOL;
}
if (is_int($Email)) {
echo "Email is Integer Yes!!!" . PHP_EOL;
} else {
echo "Email is not Integer!!!" . PHP_EOL;
}
if (is_int($Mobile)) {
echo "Mobile is Integer Yes!!!" . PHP_EOL;
} else {
echo "Mobile is not Integer!!!" . PHP_EOL;
}
//////////////////////////////
if (is_string($ID)) {
echo "ID is String Yes!!!" . PHP_EOL;
} else {
echo "ID is not String!!!" . PHP_EOL;
}
if (is_string($Email)) {
echo "Email is String Yes!!!" . PHP_EOL;
} else {
echo "Email is not String!!!" . PHP_EOL;
}
if (is_string($Mobile)) {
echo "Mobile is String Yes!!!" . PHP_EOL;
} else {
echo "Mobile is not String!!!" . PHP_EOL;
}
//$sql = "SET #p0=''$ID''; SET #p1=''$Email''; SET #p2=''$Mobile''; CALL `getRecord`(#p0, #p1, #p2);";
//$sql = "CALL getRecord(''$ID'',''$Email'',''$Mobile'');";
//$sql = "CALL getRecord(" + "'$ID'" + "," + "'$Email'" + "," + "'$Mobile'" + ");";
//$sql = "CALL getRecord(" + "'$ID'" + "," + "'$Email'" + "," + "'$Mobile'" + ");";
//$sql = "CALL getRecord('2261','saleh#gmail.com','+989999999999');";//this state is good word too, and show me true query
$sql = "CALL getRecord('$ID','$Email','$Mobile');";
if (mysqli_connect_errno()) {
echo "Failed to connect MySQL server" . mysqli_connect_error();
}
mysqli_set_charset($con, "ascii");
$resualt = mysqli_query($con, $sql);
$records = array();
while ($row = mysqli_fetch_array($resualt)) {
$record = array();
$record['ID'] = $row['ID'];
$record['Name'] = $row['Name'];
$record['Family'] = $row['Family'];
$record['BirthDate'] = $row['BirthDate'];
$record['Email'] = $row['Email'];
$record['Mobile'] = $row['Mobile'];
$records[] = $record;
}
echo json_encode($records);
mysqli_close($con);
}
Sql side and procedure code :
DELIMITER $$
CREATE PROCEDURE `getRecord` (IN ID VARCHAR(166) CHARACTER SET ascii, IN EMail VARCHAR(166) CHARACTER SET ascii , IN Mobile VARCHAR(166) CHARACTER SET ascii)
BEGIN
DECLARE CheckMe VARCHAR(166);
DECLARE CountRecords INT;
SET CheckMe = ( SELECT Count(*) FROM persons WHERE persons.Email = Email AND persons.Mobile = Mobile);
IF CheckMe = 1 THEN
SELECT * FROM persons WHERE persons.ID = ID;
ELSE
SELECT * FROM persons WHERE persons.ID = 'xxxx';
END IF ;
END $$
DELIMITER ;
I want to send data to my database (group_id, user_id and group_name) but only the first two are getting into the database. When I var_dump $groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname); it gives me the correct group_name. What am I doing wrong?
When I replace '" . $db->conn->real_escape_string($this->Invitation_group_name) . "' with a random word it is working well..
PHP
$groupinvitation = new GroupInvitation();
if (isset($_POST["Accept"])) {
try {
$group_id = mysql_real_escape_string($_POST["group_id"]);
$groupinfo = $group->GetGroupInfoByGroupId($group_id);
$groupname = $groupinfo['group_name'];
$requestnumber = mysql_real_escape_string($_POST['acceptID']);
$groupinvitation->AddAsGroupMember($number, $group_id);
$groupinvitation-> AcceptGroupRequest($requestnumber);
$groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname);
$feedback = "Awesome, You just added a friend!";
} catch(Exception $e) {
$feedback = $e -> getMessage();
}
}
DECLARATIONS:
class GroupInvitation
{
private $m_sGroup_invitation_group_name;
public function __set($p_sProperty, $p_vValue)
{
switch($p_sProperty)
{
case "Invitation_group_name":
$this->m_sGroup_invitation_group_name = $p_vValue;
break;
}
}
public function __get($p_sProperty)
{
switch($p_sProperty)
{
case "Invitation_group_name":
return $this->m_sGroup_invitation_group_name ;
break;
}
}
FUNCTION:
public function AddAsGroupMember($number, $group_id)
{
$db = new Db();
$insert = "INSERT INTO tblgroup_member(
group_id,
user_id,
group_name
) VALUES (
'" . $db->conn->real_escape_string($group_id) . "',
'" . $db->conn->real_escape_string($number) . "',
'" . $db->conn->real_escape_string($this->Invitation_group_name) . "'
)";
$db->conn->query($insert);
}
Try changing
$groupinvitation->AddAsGroupMember($number, $group_id);
$groupinvitation-> AcceptGroupRequest($requestnumber);
$groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname);
to
$groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname);
$groupinvitation->AddAsGroupMember($number, $group_id);
$groupinvitation-> AcceptGroupRequest($requestnumber);
You could be setting the property after the insert.