Send 2 variables through url - javascript

I send 2 variables by url:
var http = false;
http = new XMLHttpRequest();
function carrega(){
var nome = document.getElementById('CodigoUtente').value;
var nomes = document.getElementById('Nome').value;
var url_="conexao4?CodigoUtente="+nome+"&Nome="+nomes;
http.open("GET",url_,true);
http.onreadystatechange=function(){
if(http.readyState==4){
var retorno = JSON.parse(http.responseText);
document.getElementById('CodigoUtente').value = retorno.CodigoUtente;
document.getElementById('Nome').value = retorno.Nome;
document.getElementById('DataNasc').value = retorno.DataNasc;
document.getElementById('Sexo').value = retorno.Sexo;
document.getElementById('Estadocivil').value = retorno.Estadocivil;
document.getElementById('Nacionalidade').value = retorno.Nacionalidade;
document.getElementById('Responsavel').value = retorno.Responsavel;
document.getElementById('Parentesco').value = retorno.Parentesco;
document.getElementById('Contato').value = retorno.Contato;
}
}
http.send(null);
}
in the connection page4 I have the php that receives the variables:
$CodigoUtente = $_GET['CodigoUtente'];
$Nome = $_GET['Nome'];
if((isset($CodigoUtente)) && (isset($Nome))){
$query= "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes WHERE (CodigoUtente = '$CodigoUtente') OR (Nome LIKE '%$Nome%')";
$resultados = $conn->query($query);
$json = array();
while ($rowResultados = $resultados->fetch_assoc()) {
$dados = array(
'CodigoUtente' => $rowResultados['CodigoUtente'],
'Nome' => $rowResultados['Nome'],
'DataNasc' => $rowResultados['DataNasc'],
'Sexo' => $rowResultados['Sexo'],
'Estadocivil' => $rowResultados['Estadocivil'],
'Nacionalidade' => $rowResultados['Nacionalidade'],
'Responsavel' => $rowResultados['Responsavel'],
'Parentesco' => $rowResultados['Parentesco'],
'Contato' => $rowResultados['Contato']
);
$json = $dados;
}
echo json_encode($json);
}
The problem is that they only work if you fill in the two inputs and intended that they return the data from the database only when filling one of them.
Curious_Mind was saying this way?
$where_caluse = array();
if(isset($_GET['CodigoUtente'])){
$where_caluse[] = "CodigoUtente = '".$_GET['CodigoUtente']."'";
}
if(isset($_GET['Nome'])){
$where_caluse[] = "Nome = '".$_GET['Nome']."'";
}
$where = array_filter($where_caluse);
$query = "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes";
$resultados = $conn->query($query);
if(!empty($where)){
$final_where = count($where) > 1 ? implode(' OR ', $where) : end($where);
$query = "$query WHERE ". $final_where;
$json = array();
while ($rowResultados = $resultados->fetch_assoc()) {
$dados = array(
'CodigoUtente' => $rowResultados['CodigoUtente'],
'Nome' => $rowResultados['Nome'],
'DataNasc' => $rowResultados['DataNasc'],
'Sexo' => $rowResultados['Sexo'],
'Estadocivil' => $rowResultados['Estadocivil'],
'Nacionalidade' => $rowResultados['Nacionalidade'],
'Responsavel' => $rowResultados['Responsavel'],
'Parentesco' => $rowResultados['Parentesco'],
'Contato' => $rowResultados['Contato']
);
$json = $dados;
}
echo json_encode($json);
}
I tried to apply the form it said, but it is not working, it gives 500 error when I send the values ​​of the variables.
Can you help fix the problem? I have a form to be populated with these values

$where = " where ";
$CodigoUtente = 'a';
$Nome = '';
if($CodigoUtente != '' && $Nome != '')
{
$where .= "CodigoUtente = '$CodigoUtente' OR Nome = '$Nome';";
}else if ($CodigoUtente != ''){
$where .= "CodigoUtente = '$CodigoUtente';";
}else{
$where .= " Nome = '$Nome';";
}
$query = "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes".$where;
echo $query;

You can try like this way before making you sql query. This will help you to handle WHERE with OR condition, without OR condition and without any condition at all.
$where = array();
$_GET['CodigoUtente'] = 'Sany';
$_GET['Nome'] = 'Bruno';
if(isset($_GET['CodigoUtente'])){
$where[] = "CodigoUtente = '".$_GET['CodigoUtente']."'";
}
if(isset($_GET['Nome'])){
$where[] = "Nome = '".$_GET['Nome']."'";
}
$sql = "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes";
if(!empty($where)){
$final_where = count($where) > 1 ? implode(' OR ', $where) : end($where);
$sql = "$sql WHERE ". $final_where;
}
echo $sql;
DEMO: https://3v4l.org/phZGW

Related

API receiving Half Data

I have a PHP API but when I send data to it using a post or get request the API receives half data, I don't know what the issue is. this same API works on the localhost but gives error on the Public server.
API sendrequset URL:
https://peer.infusiblecoder.com/android/loanapp/sendrequesttoperson.php?request_is_seen=hjhj&loan_request_code=100&req_status=hjh&request_sender_user_name=ghjgjh&request_reciver_user_name=hjhjh&request_sender_user_id=jkjkj&request_reciver_user_id=hjhj&request_time_stamp=ghhgjhh
And this is my Api sendrequesttoperson.php
<?php
require 'db.php';
if(isset( $_GET["$req_status_db"]) && isset($_GET["$loan_request_code_db"]) && isset($_GET["$request_sender_user_name_db"]) && isset($_GET["$request_reciver_user_name_db"]) && isset($_GET["$request_sender_user_id_db"]) && isset($_GET["$request_reciver_user_id_db"]) && isset($_GET["$request_is_seen_db"]) && isset($_GET["$request_time_stamp_db"])){
$loan_request_code = $_GET["$loan_request_code_db"];
$request_sender_user_name = $_GET["$request_sender_user_name_db"];
$request_reciver_user_name = $_GET["$request_reciver_user_name_db"];
$request_sender_user_id = $_GET["$request_sender_user_id_db"];
$request_reciver_user_id = $_GET["$request_reciver_user_id_db"];
$request_time_stamp = $_GET["$request_time_stamp_db"];
$request_is_seen = $_GET["$request_is_seen_db"];
$req_status = $_GET["$req_status_db"];
$sql = "select * from $table_requests where $loan_request_code_db like '".$loan_request_code."';";
$result = mysqli_query($con, $sql);
$response = array();
if(mysqli_num_rows($result) > 0){
$code = "failed";
$message = "Request already exists";
array_push($response, array("code" => $code, "message" => $message));
echo json_encode($response);
} else {
$sql = "INSERT INTO $table_requests VALUES (NULL,'$loan_request_code','$request_sender_user_name','$request_reciver_user_name','$request_sender_user_id','$request_reciver_user_id','$request_time_stamp','$request_is_seen','$req_status')";
if (mysqli_query($con, $sql)) {
$code = "success";
$message = "Request sent";
array_push($response, array("code" => $code, "message" => $message));
echo json_encode($response);
echo "Request sent successfully";
} else {
$code = "failed";
$message = "Error: " . $sql . "<br>" . mysqli_error($con);
array_push($response, array("code" => $code, "message" => $message));
echo json_encode($response);
}
//$message = "Thank you for registration";
// array_push($response, array("code" => $code, "message" => $message));
// echo json_encode($response);
}
mysqli_close($con);
}else{
$loan_request_code = $_GET["$loan_request_code_db"];
$request_sender_user_name = $_GET["$request_sender_user_name_db"];
$request_reciver_user_name = $_GET["$request_reciver_user_name_db"];
$request_sender_user_id = $_GET["$request_sender_user_id_db"];
$request_reciver_user_id = $_GET["$request_reciver_user_id_db"];
$request_time_stamp = $_GET["$request_time_stamp_db"];
$request_is_seen = $_GET["$request_is_seen_db"];
$req_status = $_GET["$req_status_db"];
$myresponse = 'Enter missing fields_'.$request_sender_user_name."_".$loan_request_code."_".$request_reciver_user_name."_".$request_sender_user_id."_".$request_reciver_user_id."_".$request_time_stamp."_".$request_is_seen."_".$req_status."_";
echo json_encode($myresponse);
}
?>
And this is my db.php file required for the variable names and db connection
<?php
$host = "localhost";
$db_user = "ur5kq7835fnc4";
$db_password ="ch%2#3/^c<1b";
$db_name = "dbhrzz2e49skck";
//Folder Path
$mainpath = "http://192.168.0.101/android/loanapp/";
$profilepic_folder = "profilepics/";
$fileupload_folder="uploadedFiles/";
$fileuploadfullpath_folder="uploadedFiles/";
// loan request statuses {"pending", "rejected","accepted","awaiting money", "paid out", "completed"};
// Table RegisteredUser attributes:
$table_user = "registered_users";
$user_id_db = "user_id";
$firstname_db = "firstname";
$lastname_db = "lastname";
$address_db = "address";
$whatyoupretend_db = "whatyoupretend";
$fieldofactivity_db = "fieldofactivity";
$phone_db = "phone";
$email_db = "email";
$password_db = "password";
$status_db = "status";
$user_img_url_db = "user_img_url";
// Table LoanRequest attributes:
$table_loan_request = "loan_request";
$loan_id_db = "loan_id";
$loan_request_code_db = "loan_request_code";
$user_full_name_db = "user_full_name";
$user_img_url_request_db = "user_img_url_request";
$loan_amount_db = "loan_amount";
$loan_purpose_db = "loan_purpose";
$loan_collateral_db = "loan_collateral";
$loan_market_value_db = "loan_market_value";
$loan_type_db = "loan_type";
$loan_due_date_db = "loan_due_date";
$loan_doc_urls_db = "loan_doc_urls";
$loan_borrowing_rate_db ="loan_borrowing_rate";
$loan_loan_ratio_db ="loan_loan_ratio";
$loan_status_db = "loan_status";
$loan_paid_out_date_db ="loan_paid_out_date";
$loan_duration_db = "loan_duration";
//loan_duration
//loan_paid_out_date
// Table Requests
$table_loan_request = "loan_request";
$loan_id_db = "loan_id";
$loan_request_code_db = "loan_request_code";
$user_full_name_db = "user_full_name";
$user_img_url_request_db = "user_img_url_request";
$loan_amount_db = "loan_amount";
$loan_purpose_db = "loan_purpose";
$loan_collateral_db = "loan_collateral";
$loan_market_value_db = "loan_market_value";
$loan_type_db = "loan_type";
$loan_due_date_db = "loan_due_date";
$loan_doc_urls_db = "loan_doc_urls";
$loan_borrowing_rate_db ="loan_borrowing_rate";
$loan_loan_ratio_db ="loan_loan_ratio";
$loan_status_db = "loan_status";
$loan_lender_id_db = "loan_lender_id";
$loan_paid_out_date_db ="loan_paid_out_date";
$loan_duration_db = "loan_duration";
/*
Table User attributes:
tbname = registered_users
user_id
firstname
lastname
address
whatyoupretend
fieldofactivity
phone
email
password
status [true,false]
user_img_url
*/
/*
Table LoanRequest attributes:
tbname = loan_request
loan_id
loan_request_code
user_full_name
loan_amount
loan_purpose
loan_collateral
loan_market_value
loan_type
loan_due_date
loan_doc_vehicle_id_url
loan_doc_owner_id_url
loan_doc_insurance_url
loan_status
Vehicle ID,Owner´s ID,Insurance
*/
/*
Table Requests attributes:
tbname = requests
request_id
loan_request_code
request_sender_user_name
request_reciver_user_name
request_sender_user_id
request_reciver_user_id
request_time_stamp
request_is_seen
*/
$con = mysqli_connect($host, $db_user,$db_password,$db_name);
if (!$con){
die("connection failed". mysqli_connect_error());
}
/*
else{
echo "connected susscesful";
}
*/
?>
it gives this result
The problem is $_GET["$req_status_db"]
It should be $_GET["req_status_db"]
You will have to remove $ from all the $_GET keys.
Also, you do not have req_status_db as query param in the URL you have shared.

How do I submit form without page reload taking into consideration the php script?

So basically I have to work on this loan calculator loancalc.000webhostapp.com
I have looked at other pages on this site "how to submit form without page reload?" but this isn't completely relevant to what i'm working on. So far i've added this into the jquery part of the page...
jQuery('qis-register').on('submit', 'input', function(){
event.preventDefault();
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
return false;
}
else{
}
if (email == ""){
$("input#youremail").focus;
return false;
}
});
But i'm told there is also two other scripts that I need to work with, I'm not really too experienced with php so not sure what's going on, the two php scripts I have to work with are called quick-interest-slider.php and register.php,
//qis_verify_application in register.php
function qis_verify_application(&$values, &$errors) {
$application = qis_get_stored_application();
$register = qis_get_stored_application_messages();
$arr = array_map('array_shift', $application);
foreach ($arr as $key => $value) {
if ($application[$key]['type'] == 'multi') {
$d = explode(",",$application[$key]['options']);
foreach ($d as $item) {
$values[$key] .= $values[$key.$item];
}
}
if ($application[$key]['required'] == 'checked' && $register['use'.$application[$key]['section']] && (empty($values[$key]) || $values[$key] == 'Select...'))
$errors[$key] = 'error';
}
$filenames = array('identityproof','addressproof');
foreach($filenames as $item) {
$tmp_name = $_FILES[$item]['tmp_name'];
$name = $_FILES[$item]['name'];
$size = $_FILES[$item]['size'];
if (file_exists($tmp_name)) {
if ($size > $register['attach_size']) $errors['attach'.$item] = $register['attach_error_size'];
$ext = strtolower(substr(strrchr($name,'.'),1));
if (strpos($register['attach_type'],$ext) === false) $errors['attach'.$item] = $register['attach_error_type'];
}
}
return (count($errors) == 0);
}
//qis_process_application in register.php
function qis_process_application($values) {
global $post;
$content='';
$register = qis_get_stored_register ('default');
$applicationmessages = qis_get_stored_application_messages();
$settings = qis_get_stored_settings();
$auto = qis_get_stored_autoresponder();
$application = qis_get_stored_application();
$message = get_option('qis_messages');
$arr = array_map('array_shift', $application);
if ($message) {
$count = count($message);
for($i = 0; $i <= $count; $i++) {
if ($message[$i]['reference'] == $values['reference']) {
$values['complete'] = 'Completed';
$message[$i] = $values;
update_option('qis_messages',$message);
}
}
}
$filenames = array('identityproof','addressproof');
$attachments = array();
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
add_filter( 'upload_dir', 'qis_upload_dir' );
$dir = (realpath(WP_CONTENT_DIR . '/uploads/qis/') ? '/uploads/qis/' : '/uploads/');
foreach($filenames as $item) {
$filename = $_FILES[$item]['tmp_name'];
if (file_exists($filename)) {
$name = $values['reference'].'-'.$_FILES[$item]['name'];
$name = trim(preg_replace('/[^A-Za-z0-9. ]/', '', $name));
$name = str_replace(' ','-',$name);
$_FILES[$item]['name'] = $name;
$uploadedfile = $_FILES[$item];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
array_push($attachments , WP_CONTENT_DIR .$dir.$name);
}
}
remove_filter( 'upload_dir', 'qis_upload_dir' );
$content = qis_build_complete_message($values,$application,$arr,$register);
qis_send_full_notification ($register,$values,$content,true,$attachments);
qis_send_full_confirmation ($auto,$values,$content,$register);
}
function qis_loop in quick-interest-slider.php
function qis_loop($atts) {
$qppkey = get_option('qpp_key');
if (!$qppkey['authorised']) {
$atts['formheader'] = $atts['loanlabel'] = $atts['termlabel'] = $atts['application'] = $atts['applynow'] = $atts['interestslider'] = $atts['intereselector']= $atts['usecurrencies'] = $atts['usefx'] = $atts['usedownpayment'] = false;
if ($atts['interesttype'] == 'amortization' || $atts['interesttype'] == 'amortisation') $atts['interesttype'] = 'compound';
}
global $post;
// Apply Now Button
if (!empty($_POST['qisapply'])) {
$settings = qis_get_stored_settings();
$formvalues = $_POST;
$url = $settings['applynowaction'];
if ($settings['applynowquery']) $url = $url.'?amount='.$_POST['loan-amount'].'&period='.$_POST['loan-period'];
echo "<p>".__('Redirecting....','quick-interest-slider')."</p><meta http-equiv='refresh' content='0;url=$url' />";
die();
// Application Form
} elseif (!empty($_POST['qissubmit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_form($formvalues, $formerrors)) {
return qis_display($atts,$formvalues, $formerrors,null);
} else {
qis_process_form($formvalues);
$apply = qis_get_stored_application_messages();
if ($apply['enable'] || $atts['parttwo']) return qis_display_application($formvalues,array(),'checked');
else return qis_display($atts,$formvalues, array(),'checked');
}
// Part 2 Application
} elseif (!empty($_POST['part2submit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_application($formvalues, $formerrors)) {
return qis_display_application($formvalues, $formerrors,null);
} else {
qis_process_application($formvalues);
return qis_display_result($formvalues);
}
// Default Display
} else {
$formname = $atts['formname'] == 'alternate' ? 'alternate' : '';
$settings = qis_get_stored_settings();
$values = qis_get_stored_register($formname);
$values['formname'] = $formname;
$arr = explode(",",$settings['interestdropdownvalues']);
$values['interestdropdown'] = $arr[0];
$digit1 = mt_rand(1,10);
$digit2 = mt_rand(1,10);
if( $digit2 >= $digit1 ) {
$values['thesum'] = "$digit1 + $digit2";
$values['answer'] = $digit1 + $digit2;
} else {
$values['thesum'] = "$digit1 - $digit2";
$values['answer'] = $digit1 - $digit2;
}
return qis_display($atts,$values ,array(),null);
}
}
Do I have to edit any of the php and I also don't know what I have to write considering the php.
You can use what is called Ajax to submit the data to the server via POST.
Create a button and give it a class of qis-register, then give each of your input fields a class that matches it's name. Then just add that field to the data object that I have following the format within it.
jQuery(document).on('click', '.qis-register', function(){
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
}
else if (email == ""){
$("input#youremail").focus;
}
else{
jQuery.ajax({
type: "POST",
url: "your_php_here.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
});

How to embed Javascript function in restful api in php?

I have the following code in one of api files(DispatchJob_Public) and i need ajax here to call the other file(selectDriverForJobResult) after 2 minutes. I can do that in php with sleep(), but that will keep the server busy. Ajax call is at the end of the php code. Can i embed js in api code? Or is there any alternate to do what i am trying to do.
Moreover i have got response from the first file(DispatchJob_Public), but no response from the second file(selectDriverForJobResult) when i called the endpoint in postman. Because the call wasn't made. If the second file was called, it should have return some response. The strange thing is that i get response from second file when i run it in browser. I think that is because the browser supports the javascript but the call made from android to the end point doesn't support that.
Please can i get any solution for this?
<?php
include_once ('connection.php');
include_once ('fcm_notification.php');
//error_reporting(E_ERROR | E_PARSE);
$user_id = $_REQUEST["user_id"];
$customer_name = $_REQUEST["customer_name"];
$group_id_fk = $_REQUEST["group_id_fk"];
$readynow_checkbox = $_REQUEST["readynow_checkbox"];
$job_points = '';
date_default_timezone_set('Australia/Melbourne');
$date = date('Y-m-d H:i:s');
if(strcasecmp($benefits_type, 'Points') == 0){
if(strcasecmp($fixed_price, '') == 0){
$fixed_price_new = $estimated_price;
}else{
$fixed_price_new = $fixed_price;
}
$sql_job_points = "SELECT `points` FROM `hg_job_points` WHERE '$fixed_price_new' BETWEEN `min_price` AND `max_price`";
$res_jobPoints = mysqli_query($conn, $sql_job_points);
$row_job_points = $res_jobPoints->fetch_assoc();
$job_points = $row_job_points["points"];
}
if(strcasecmp($commission_percent, 'Amount') != 0 && strcasecmp($fixed_price, '') != 0){
$commision_price = ($commission_percent / 100) * $fixed_price;
}
//insert job in job table
$sql = "INSERT INTO `hg_jobs`(`customer_name`, `pickup_address`, `dropoff_address`, `customer_phone`, `instruction`,
`via`, `user_id_fk`, `group_id_fk`, `pickup_time`, `flight_no`, `car_type`, `post_time`)
VALUES ('$customer_name', '$pickup_address', '$dropoff_address', '$customer_phone', '$instruction', '$via', '$user_id', '$group_id_fk',
'$pick_time', '$flight_no', '$car_type', '$date')";
if(mysqli_query($conn, $sql)){
//get job id from jobs table
$job_id = $conn->insert_id;
//insert new record in advance job table
$sql_adv = "INSERT INTO `hg_job_details`(`no_of_passenger`, `no_of_bags`, `child_seats`,
`car_type_specific`, `job_type`, `job_price`, `estimated_amount`, `payment_type`, `benefits_type`, `benefit_percent`,
`benefit_amount`, `job_points`, `ready_now_job`, `job_id_fk`)
VALUES ('$passenger','$bags','$child_seats','$car_type_specific','$job_type','$fixed_price', '$estimated_price',
'$payment_type','$benefits_type','$commission_percent','$commision_price', '$job_points', '$readynow_checkbox', '$job_id') ";
$res_adv = mysqli_query($conn, $sql_adv);
if($res_adv){
echo json_encode(Array('message' => 'job success'));
//get black list users
$sql_black = "SELECT blacklist_user_fk FROM hg_black_list WHERE user_id_fk = '$user_id'";
$res_black = mysqli_query($conn,$sql_black);
//if specif type car is any
if(strcasecmp($car_type_specific, 'ANY') == 0){
if ($res_black->num_rows > 0) {
//get all fcm key and send notification (if blacklist table not empty)
$sql = "SELECT ft.fcm_token from hg_user_notify_token ft
JOIN hg_users AS u ON u.user_id = ft.user_id_fk
JOIN hg_car_details AS cd ON u.user_id = cd.user_id_fk
WHERE u.user_id != '$user_id' AND cd.car_type = '$car_type' AND u.user_id !=
(SELECT blacklist_user_fk FROM hg_black_list WHERE user_id_fk = '$user_id') ";
$result = $conn->query($sql);
while ($keys = mysqli_fetch_assoc($result)){
$token = $keys['fcm_token'];
$title = 'HIRENGO';
$message = 'New Job Request Received';
$activity_to_open = 'new job';
sendPushNotification($token, $title, $message,$activity_to_open);
}
}else{
//get all fcm key and send notification (if blacklist table empty)
$sql = "SELECT ft.fcm_token from hg_user_notify_token ft
JOIN hg_users AS u ON u.user_id = ft.user_id_fk
JOIN hg_car_details AS cd ON u.user_id = cd.user_id_fk
WHERE u.user_id != '$user_id' AND cd.car_type = '$car_type'";
$result = $conn->query($sql);
while ($keys = mysqli_fetch_assoc($result)){
$token = $keys['fcm_token'];
$title = 'HIRENGO';
$message = 'New Job Request Received';
$activity_to_open = 'new job';
sendPushNotification($token, $title, $message,$activity_to_open);
}
}
}else{
//if specific car type
if ($res_black->num_rows > 0) {
//get all fcm key and send notification (if blacklist table not empty)
$sql = "SELECT ft.fcm_token from hg_user_notify_token ft
JOIN hg_users AS u ON u.user_id = ft.user_id_fk
JOIN hg_car_details AS cd ON u.user_id = cd.user_id_fk
WHERE u.user_id != '$user_id' AND cd.car_type = '$car_type'
AND cd.car_type_specific = '$car_type_specific' AND u.user_id !=
(SELECT blacklist_user_fk FROM hg_black_list WHERE user_id_fk = '$user_id') ";
$result = $conn->query($sql);
while ($keys = mysqli_fetch_assoc($result)){
$token = $keys['fcm_token'];
$title = 'HIRENGO';
$message = 'New Job Request Received';
$activity_to_open = 'new job';
sendPushNotification($token, $title, $message,$activity_to_open);
}
}else{
//get all fcm key and send notification (if blacklist table empty)
$sql = "SELECT ft.fcm_token from hg_user_notify_token ft
JOIN hg_users AS u ON u.user_id = ft.user_id_fk
JOIN hg_car_details AS cd ON u.user_id = cd.user_id_fk
WHERE u.user_id != '$user_id' AND cd.car_type = '$car_type'
AND cd.car_type_specific = '$car_type_specific'";
$result = $conn->query($sql);
while ($keys = mysqli_fetch_assoc($result)){
$token = $keys['fcm_token'];
$title = 'HIRENGO';
$message = 'New Job Request Received';
$activity_to_open = 'new job';
sendPushNotification($token, $title, $message,$activity_to_open);
}
}
}
?>
<script>
function callDispatch()
{
nIntervId = window.setInterval(myCallback, 5000);
var baseUrl = document.location.origin;
function myCallback()
{
var user_id = '<?=$GLOBALS["user_id"];?>';
var job_id = '<?=$job_id;?>';
$.ajax({
url: baseUrl+'/android/selectDriverForJobResult.php',
type: 'POST',
dataType : 'json',
data: {'user_id': user_id, 'job_id': job_id} ,
success: function(response) {
clearInterval(nIntervId);
var resp = response.toString();
if (resp.includes('true') === true)
{
console.log('true'+ resp);
}
else
{
console.log(resp);
}
},
error: function(response)
{
console.log('Error in ajax'+response.statusText);
clearInterval(nIntervId);
}
});
}
}
callDispatch();
</script>
<?php
}
} else{
echo json_encode(Array('message' => 'error job post'));
}
$conn->close();
?>

Break an array inside array php

I have a function which allows me to save dropped objects for each process in loop. Fiddle here The problem i am creating an array for each process and store dropped items inside. Function i use to save droped items:
<script>
var LISTOBJ = {
saveList: function() {
$(".leader").each(function() {
var listCSV = [];
$(this).find("li").each(function(){
listCSV.push($(this).text());
});
var values = listCSV.join(', ');
$(".output").append("<input type='hidden' name='leader[]' value='"+values+"' />");
$("#output").append("<p>"+values+"</p>");
console.debug(listCSV);
});
}
}
</script>
And what i get after printing saved objects:
Array ( [0] => aaronjames,adelyn [1] => benny,bryanooi )
I want to store names in the database and im able to do it but it stores an array. So i am looking a way to break an array inside array, instead of storing a full array.
I have 2 tables: 'project' and 'process'. I am trying to insert names into 'process' table. I am able to do so. but it stays as an array.
Here is function i am using to store received value inside database. I am generating project number and using foreach to assign names for each process
function insertRecord(){
global $holdcode,$holdtitle,$projLeader,$projChecker,$holdremark,$holdprocess,$holdnumber,$procLeader,$procChecker, $prodStuff;
// To protect MySQL injection (more detail about MySQL injection)
$holdcode = cleanInputData($holdcode);
$holdtitle = cleanInputData($holdtitle);
$projLeader = cleanInputData($projLeader);
$projChecker = cleanInputData($projChecker);
$holdremark = cleanInputData($holdremark);
$holdcode = mysql_real_escape_string($holdcode);
$holdtitle = mysql_real_escape_string($holdtitle);
$projLeader = mysql_real_escape_string($projLeader);
$projChecker = mysql_real_escape_string($projChecker);
$holdremark = mysql_real_escape_string($holdremark);
$result = getLastProjectNo();
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if(mysql_num_rows($result) == 0)
{
$year = date("y");
$month = date("m");
$number = sprintf("%04d", 1);
$yearStr = strval($year);
$monthStr = strval($month);
$numberStr = strval($number);
$projectNo = $yearStr . $monthStr . $numberStr;
}
else{
if ($row_last = mysql_fetch_array($result))
{
$row_last[0] = cleanOutputData($row_last[0]);
$projectNo = $row_last[0];
$extractedNumberStr = substr($projectNo, -4);
$extractedYearMonthStr = substr($projectNo, 0, 4);
$year = date("y");
$month = date("m");
$yearStr = strval($year);
$monthStr = strval($month);
$currentYearMonthStr = $yearStr . $monthStr;
if($extractedYearMonthStr == $currentYearMonthStr)
{
$extractedNumber = intval($extractedNumberStr);
$extractedNumber++;
$extractedNumber = sprintf("%04d", $extractedNumber);
$extractedNumberStr = strval($extractedNumber);
$projectNo = $currentYearMonthStr . $extractedNumberStr;
}
else
{
$number = sprintf("%04d", 1);
$projectNo = $currentYearMonthStr . $number;
}
}
}
mysql_set_charset('utf8');
//query result
$result = insertProject($projectNo,$_SESSION['login_user'],$holdcode,$holdtitle,$projLeader,$projChecker,$holdremark);
// Check result
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$result = getLastProjectNo();
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$result = getLastProjectNo();
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if ($row_last = mysql_fetch_array($result))
{
$row_last[0] = cleanOutputData($row_last[0]);
$projectNo = $row_last[0];
if (is_array($holdprocess) || is_object($holdprocess))
{
foreach( $holdprocess as $code => $eq )
{
$record = insertProcess($projectNo,$eq,$holdnumber[$code],$procLeader[$code],$procChecker[$code], $prodStuff[$code]);
if (!$record) {
die('Invalid query: ' . mysql_error());
}
}
}
}
}
What I want is to break an array inside array.For example i have Array ( [0] => aaronjames,adelyn [1] => benny,bryanooi ) i need to break [0] => aaronjames,adelyn into something that will allow me to store each name for each row in the table
Let me show you a way to read array value:
for($x = 0; $x < count($array_name); $x++) {
echo $array_name[$x];
echo "<br>";
}
If you need to access an array of objects then, try this
foreach($array_name as $obj){
$status = $obj->status;
}
If you receive a combined string (like 'aaronjames,adelyn') from array, then you can split the combined string using 'explode()' function of Php
<?php
$str = "aaronjames,adelyn";
$str_array=(explode(",",$str));
for($i=0;$i<count($str_array);$i++)
echo $str_array[$i]."<br/>";
?>

I can not get data from jQuery muscles

I am learning tutorial, but I understand that the author made a mistake / mistakes.
The data is sent via GET in php and write, but do not turn back.
JavaScript:
function loadAllPost() {
var divs = $("#posts");
$.get("twitor.php?action=last", function() {
var posts = [];
for(var i = 0; i < posts.length; i++) {
var newPost = addNewPost(posts[i].name, posts[i].text, posts[i].date);
posts.push(newPost);
}
divs.children().remove();
divs.append(posts);
});
}
$(function() {
loadAllPost();
setInterval(loadAllPost, 5000);
$("#submit").click(function() {
var newPostName = $("#name").val();
var newPostText = $("#text").val();
var newPostDate = (new Date()).toLocaleString();
var newPost = addNewPost(newPostName, newPostText, newPostDate);
newPost.hide();
$("#posts").append(newPost);
newPost.slideToggle();
$("name").val("");
$("text").val("");
$.post("twitor.php?action=new", {
text: newPostText,
name: newPostName
});
});
});
Ie like php sends data, but does not have JS embeds them in HTML.
PHP:
if ($_GET['action'] == 'new') {
addNewPost();
}
elseif ($_GET['action'] == 'last') {
getLastPosts();
}
function getPDO(){
$db_host = "****";
$db_name = "****";
$db_user = "****";
$db_pass = "****";
$PDO = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
//$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
return $PDO;
}
function addNewPost(){
$params = [];
$params['name'] = $_POST['name'];
$params['text'] = htmlspecialchars($_POST['text']);
$PDO = getPDO();
$Statement = $PDO->prepare("INSERT INTO posts(`name`, `text`, `date`) VALUES (:name, :text, NOW());");
$Statement->execute($params);
}
function getLastPosts() {
$PDO = getPDO();
$Statement = $PDO->query("SELECT * FROM posts ORDER BY date DESC LIMIT 15");
if(!$Statement) return;
$posts = $Statement->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($posts);
}

Categories

Resources