I have a react app that makes a post request to the following code.
<?php
require_once('dbSURL.php');
$stm = $db->prepare("INSERT INTO urlshortener (longUrl, shortId, userIp, userCountry, userCity, userOS, userAgent, createDate) VALUES (:longUrl, :shortId, :userIp, :userCountry, :userCity, :userOS, :userAgent, :createDate)");
$stm->bindParam(':longUrl', $_POST['longUrl']);
$stm->bindParam(':shortId', $_POST['shortId']);
$stm->bindParam(':userIp', $_POST['userIp']);
$stm->bindParam(':userCountry', $_POST['userCountry']);
$stm->bindParam(':userCity', $_POST['userCity']);
$stm->bindParam(':userOS', $_POST['userOS']);
$stm->bindParam(':userAgent', $_POST['userAgent']);
$stm->bindParam(':createDate', $_POST['createDate']);
if ($stm->execute()) {
echo "success";
} else {
echo "failure: ".$stm->errorInfo()[2];
};
// $stm->execute();
// echo 'Error: %s.\n', $stm->errorCode(), $stm->errorInfo();
?>
After checking the request from dev tools I can see that the data are sent but when I get the data from the database all the fields are null.
Any help?
Related
I have an API to do an action for a site.
/api/api.php?api=server&ver=1.0&key=**&cmd=ADD_OBJECT,862011228001930
The API works and does what it needs to be done. The API information is populated from a form I have. the form also needs to upload information to MYSQL database using SQL
I have the following SQL
$sql = "INSERT INTO tracking_units SET
status = 'Tech',
unit_nr = '".$unit_nr."',
imei = '".$imei."',
sysdate = '".$date."',
systime = '".$time."',
controller = '".$slname."',
branch = 'JHB',
client = 'eTrack'";
if ($conn->query($sql) === TRUE)
{$last_id = mysqli_insert_id($conn); //Retrieve the last ID of the record
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
header("Location: http://***/api/api.php?api=server&ver=1.0&key=***&cmd=ADD_OBJECT,$imei");
The above works as the header runs the API, but once the API is completed I would like to redirect the page to another html page. Is this possible with me running the header command.
I am very new to API's and not sure how else I can run the API after the SQL command and then use the header to divert to another page
I have found this to work
$ch = curl_init("http://***/api/api.php?api=server&ver=1.0&key=***&cmd=ADD_OBJECT,$imei,$unit_nr,false,2021-01-01");
curl_exec($ch);
if (curl_error($ch)) {
fwrite($ch, curl_error($ch));
}
curl_close($ch);
fclose($ch);
From a form (HTML), I send via AJAX a flag to indicate the action and a object that contains the information to save in PHP.
In the HTML file:
function Mandar_DATOS(QueHacer,OBJEvento){
// alert (OBJEvento.IdPaciente);
$.ajax({
type:'POST',
url:'./php/eventos.php?QueHacer='+QueHacer,
data:OBJEvento,success:function(msg){
if(msg){
.//mostrar en pantalla la informacion
}
},error:function(){
alert("No se guardo...");
}
});
}
in the PHP file (eventos.php)
$la_conexion = Conexion::ObtenConexion();
$QueHacer=(isset($_GET['QueHacer']))?$_GET['QueHacer']:'LEER';
switch ($QueHacer){
case 'GUARDAR':
$CadenaSQL=$la_conexion->prepare("INSERT INTO "
. "AgendaVideo(id, IdPaciente, IdMedico, title, start, end, color, textColor) "
. "VALUES(:id, :IdPaciente, :IdMedico, :title, :start, :end, :color, :textColor)");
$RESULTADO=$CadenaSQL->execute(array(
"id"=>$_POST['id'],
"IdPaciente"=>$_POST['IdPaciente'],
"IdMedico"=>$_POST['IdMedico'],
"title"=>$_POST['title'],
"start"=>$_POST['start'],
"end"=>$_POST['end'],
"color"=>$_POST['color'],
"textColor"=>$_POST['textColor']
));
echo json_encode($RESULTADO);
break;
case....
this code only returns false, but does not mark any error
If you want to return an error you need to call a method/function to output the error. Here below between the comments I'm using https://www.php.net/manual/en/pdo.errorinfo.php which just returns the error related to the last sql statement that has been run
$la_conexion = Conexion::ObtenConexion();
$QueHacer=(isset($_GET['QueHacer']))?$_GET['QueHacer']:'LEER';
switch ($QueHacer){
case 'GUARDAR':
$CadenaSQL=$la_conexion->prepare("INSERT INTO "
. "AgendaVideo(id, IdPaciente, IdMedico, title, start, end, color, textColor) "
. "VALUES(:id, :IdPaciente, :IdMedico, :title, :start, :end, :color, :textColor)");
//start error handling code
if (!$CadenaSQL) {
echo "\nPDO::errorInfo():\n";
print_r($la_conexion->errorInfo());
}
//end error handling code
$RESULTADO=$CadenaSQL->execute(array(
"id"=>$_POST['id'],
"IdPaciente"=>$_POST['IdPaciente'],
"IdMedico"=>$_POST['IdMedico'],
"title"=>$_POST['title'],
"start"=>$_POST['start'],
"end"=>$_POST['end'],
"color"=>$_POST['color'],
"textColor"=>$_POST['textColor']
));
//start error handling code
if (!$RESULTADO) {
echo "\nPDO::errorInfo():\n";
print_r($la_conexion->errorInfo());
}
//end error handling code
echo json_encode($RESULTADO);
break;
case....
Here is my ajax code.
I cannot see any error in my code, but AJAX doesn't work.
It doesn't return anything from that page...
function addCash(){
var cash =$('#cash_amount').val();
var date =$('#cash_date').val();
var debiter =$('#debiter').val();
if(cash == '' || date =='' ){
alert("Please Fill All Fields");
}
else{
$.ajax({
type: 'POST',
dataType:'JSON',
url: 'getCustomers.php',
data: 'type=cash_received&cash='+cash+'&date='+date+'& debiter='+debiter,
success:function(data){
console.log(data);
alert("Cash Added Successfully");
}
});
}
}
PHP Code "getCustomers.php"...inside a function using ajax is an issue?
$cash= $_REQUEST['cash'];
$date= $_REQUEST['date'];
$debiter= $_REQUEST['debiter'];
$query="INSERT INTO `received_payment`(`debiter`, `amount`, `date`) VALUES ('".$debiter."', '".$cash."', '".$date."')";
$result = $mysqli->query($query) or ($error=$mysqli->error.LINE);
$arr = array();
if(!$result){
$arr['result'] = isset($error) ? $error : 'error';
}
else{
$arr['result'] ="ok";
}
$json_response = json_encode($arr);
ob_clean();
echo $json_response;`
Because, you are using die anf if your query fails then your script will die and hence no response will be made. So change the below line,
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
to
$result = $mysqli->query($query) or ($error=$mysqli->error.__LINE__);
and you can return this error in response like,
if(!$result){
$arr['result'] = isset($error) ? $error : 'error';
}
Also in your insert query, fields and their values are not matching, you should use it like,
$query="INSERT INTO `received_payment` (`debiter`, `amount`, `date`)
VALUES ('".$debiter."', ".$cash."', '".$date."')";
And try to pass data from AJAX (you have space before debiter key in your data string) like,
data: {type:'cash_received',cash:cash,date:date,debiter:debiter},
An extra comma in INSERT query.
$query="INSERT INTO `received_payment`(`debiter`, `amount`, `date`,) VALUES ('".$cash."', '".$date."', '".$debiter."')";
Change to:
$query="INSERT INTO `received_payment`(`debiter`, `amount`, `date`) VALUES ('".$cash."', '".$date."', '".$debiter."')";
It is giving an error actually, but since you gave die() the code is getting exited. So you are not getting anything from Server.
in AJAX request you have mentioned accept only JSON data content. So in some case it may happens server returns response with Warning and Error if PHP error is on.
So in server side PHP script before echo response in json format you can use ob_clean() for flushing all unexpected output which is sent by error or warning.
$json_response = json_encode($arr);
ob_clean();
echo $json_response;
Please remove quotes at the end of the line
echo $json_response;`
I have a PHP file which receives a value in a POST request (it is just a test file) and insert it in MySQL. Here's the code:
require_once('config.inc.php');
$str_values = $_POST['Msg'];
$sender=$_POST['SENDER'];
$trans_log = mysqli_query($dbhandle,"INSERT INTO GPRSIN (SMSFR,SMSMSG)
VALUES ('".$sender."','".$str_values."')");
if($trans_log == 0){
//return ref no and status
echo "Insert Failed";
} else {
echo "1";
}
I want to convert it into Ruby or Sintra but I don't know how to get the POST values from the URL and insert it to MySQL.
I have seen many other posts like this, but I cannot see anything I have done wrong. I also read it could be a problem with the hosting (Heroku) so I have created a ticket, but no answer after 3 days.
Below is the code which sends the info:
(discuss.php)
<script type="text/javascript">
$(function() {
$('#ideasubmit').click(function() {
console.log();
$('#ideacontainer').append('<img src="images/loading.gif" alt="Please Wait" id="idealoading" />');
var ideatitle = $('#ideatitle').val();
var ideafbid = $('#ideafbid').val();
var idea = $('#idea').val();
$.ajax({
url: 'ajaxsqli.php',
type: 'POST',
data: 'ideatitle=' + ideatitle + '&ideafbid=' + ideafbid + '&idea=' + idea,
success: function(result) {
$('#idearesponse').remove();
$('#ideacontainer').append('<p id="idearesponse">' + result + '</p>');
$('#idealoading').fadeOut(500, function() {
$(this).remove();
});
}
});
return false;
});
});
Below here is the code file which gets the error when it sent the info:
(ajaxsqli.php)
$db = new db;
$query = "INSERT into comments(user_fbid, discuss_type, discuss_post_title, discuss_post, date) VALUES (?, ?, ?, ?, )";
$stmt = $db->stmt_init();
if($stmt->prepare($query)) {
$stmt->bind_param('iissi', $_POST['ideafbid'], 1, $_POST['ideatitle'], $_POST['idea'], date('Ymd'));
$stmt->execute();
}
if($stmt) {
echo "Thank you. We'll be in touch with you shortly!";
} else {
echo "There was a problem. Please try again later.";
}
?>
Whats odd is I had it working 3 days ago, and I went to improve some of the code and now I am unable to make it work, even if I restore the back up.
This is the full error message:
Failed to load resource: the server responded with a status of 500 (Internal Server Error) and points to ajaxsqli.php
Using Chrome Inspect Elements I can see the POST is posting the information, but no response information.
Is there anything wrong with this code ?
A 500 error usually refers to a problem in the php. Load ajaxsqli.php in the browser with the paramaters (change $_POST to $_REQUEST and then you can use the querystring. EG
$db = new db;
$query = "INSERT into comments(user_fbid, discuss_type, discuss_post_title, discuss_post, date) VALUES (?, ?, ?, ?, )";
$stmt = $db->stmt_init();
if($stmt->prepare($query)) {
$stmt->bind_param('iissi', $_REQUEST['ideafbid'], 1, $_REQUEST['ideatitle'], $_REQUEST['idea'], date('Ymd'));
$stmt->execute();
}
if($stmt) {
echo "Thank you. We'll be in touch with you shortly!";
} else {
echo "There was a problem. Please try again later.";
}
?>
Then go to http://yourhost/ajaxsqli.php?ideafbid=data&ideatitle=data&idea=data and see what the PHP error is