I have a android app which submit data through php but sometime the data insert twice when I submit the data.
I'm sure the issue is not on the app as the button is disabled once I press the button. Please help me spot my mistake. Thanks!
Following is the data inserted:
Following is my query:
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$area = $_POST['area'];
$date = $_POST['date'];
$batch = $_POST['batch'];
$workerName = $_POST['workerName'];
$remarks = $_POST['remarks'];
$time = $_POST['time'];
$tank = $_POST['tank'];
$sid= '';
$submissionDateTime = $_POST['submissionDateTime'];
require_once 'connectdb.php';
$stmt = $conn ->prepare("SELECT DISTINCT sid FROM feedingforms WHERE area = :area AND tank = :tank AND date = :date AND batch = :batch AND time = :time");
$stmt->bindParam(":area", $_POST['area']);
$stmt->bindParam(":tank", $_POST['tank']);
$stmt->bindParam(":date", $_POST['date']);
$stmt->bindParam(":batch", $_POST['batch']);
$stmt->bindParam(":time", $_POST['time']);
$stmt->execute();
$stmt->fetch();//fecth
switch ($stmt->rowCount() > 0){
case "0":
$stmt2 = $conn->prepare("INSERT INTO feedingforms(sid, area, date, batch, workerName, submissionDateTime, remarks, time, tank) VALUES(:sid, :area, :date,:batch,:workerName,:submissionDateTime, :remarks, :time,:tank)");
$stmt2->bindValue(":sid", $sid);
$stmt2->bindValue(":area", $area);
$stmt2->bindValue(":date", $date);
$stmt2->bindValue(":batch", $batch);
$stmt2->bindValue(":workerName", $workerName);
$stmt2->bindValue(":submissionDateTime", $submissionDateTime);
$stmt2->bindValue(":remarks", $remarks);
$stmt2->bindValue(":time", $time);
$stmt2->bindValue(":tank", $tank);
if ($stmt2->execute()) {
$result["success"]= "1";
$result["message"] = "success";
echo json_encode($result);
$conn = null;
exit;
break;
}else{
$result["success"]= "0";
$result["message"] = "error";
echo json_encode($result);
$conn = null;
exit;
break;
}
default:
$result["success"]= "2";
$result["message"] = "duplicate";
echo json_encode($result);
exit;
$conn = null;
}
}
?>
Related
I already create an apps that contain ListView. I uses PHP to connect between android and database. FOr now, I use MySQLi and it works. But when I convert to PDO, the data not displayed. I uses 'Log.d' to trace what the data got. Below is the result:
MySQLi (No error) - {"data":[{"report_id":19,"task_name":"ngantuk","badgeid":"12345","report_date":"04 Dec 2019",.......
PDO (not log show data)
Now, below is current code for MySQLi and PDO
MySQLi
<?php
require_once 'config.php';
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$badgeid = $_GET["badgeid"] ?? "";
$stmt = $conn->prepare("SELECT report_id, task_name, badgeid, report_date, photo_before, photo_after, report_status FROM report WHERE badgeid = '$badgeid' AND report_status = 'Pending';");
$stmt->execute();
$stmt->bind_result($report_id, $task_name, $badgeid, $report_date, $photo_before, $photo_after, $report_status);
$task = array();
while($stmt->fetch()){
$temp = array();
$temp['report_id'] = $report_id;
$temp['task_name'] = $task_name;
$temp['badgeid'] = $badgeid;
$booked = strtotime($report_date);
$report_date = date("d M Y", $booked);
$temp['report_date'] = $report_date;
$temp['photo_before'] = $photo_before;
$temp['photo_after'] = $photo_after;
$temp['report_status'] = $report_status;
array_push($task, $temp);
}
$response = array();
$response["data"] = $task;
echo json_encode($response);
?>
PDO
require_once 'configPDO.php';
$badgeid = $_GET["badgeid"] ?? "";
$stmt = $conn->prepare("SELECT report_id, task_name, badgeid, report_date, photo_before, photo_after, report_status FROM report WHERE badgeid = :badgeid AND report_status = 'Pending'");
$stmt->bindParam(':badgeid',$badgeid,PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$task = array();
while ($result) {
$temp = array();
$temp["data"] = $task;
array_push($task, $temp);
}
$response = array();
$response["data"] = $result;
echo json_encode($response);
?>
Does anyone know what is problem with my PDO code?
The mysqli code and PDO code are not the same. I copied the code from the mysqli version to the PDO version.
PDOStatement::fetch() gets one row at a time. When you take the results from fetch and put it into the condition of a while loop, you are creating an infinite loop which will eventually run out of memory.
require_once 'configPDO.php';
$badgeid = $_GET["badgeid"] ?? "";
$stmt = $conn->prepare("SELECT report_id, task_name, badgeid, report_date, photo_before, photo_after, report_status FROM report WHERE badgeid = :badgeid AND report_status = 'Pending'");
$stmt->bindParam(':badgeid',$badgeid,PDO::PARAM_STR);
$stmt->execute();
$task = [];
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
$temp = [];
$temp['report_id'] = $result['report_id'];
$temp['task_name'] = $result['task_name'];
$temp['badgeid'] = $result['badgeid'];
$booked = strtotime($result['report_date']);
$report_date = date("d M Y", $booked);
$temp['report_date'] = $result['report_date'];
$temp['photo_before'] = $result['photo_before'];
$temp['photo_after'] = $result['photo_after'];
$temp['report_status'] = $result['report_status'];
$task[] = $temp;
}
$response = [];
$response["data"] = $task;
echo json_encode($response);
Can someone point out whats wrong with my php code for calling stored procedure in mssql. The following sql query works fine in mssql studio:
EXEC updateRecord 'Record','Closed','Jon','query test4','',''
Here is the php code that Im using to try and call the updateRecord:
<?php
$Record = $_POST['record'];
$Stat = $_POST['Status'];
$Tech = $_POST['Tech'];
$Action = $POST['Action'];
$Date = date("Y/m/d");
$time = date("G:i:s");
//connect to sql
$hostname = '127.0.0.1\SQLserver';
$options = array('Database'=>'CallHistory', 'CharacterSet' => 'UTF-8');
$conn = sqlsrv_connect($hostname, $options);
if(!is_resource($conn))
{
echo 'Could not connect: ';
var_dump(sqlsrv_errors(SQLSRV_ERR_ALL));
exit(0);
}
// echo "Success";
// sqlsrv_close($conn);
// DB queries
if (empty($_POST['record']) && empty($_POST['Statut'])&&empty($_POST['Tech']) && empty($_POST['Action']))
{
echo "CHoose at least one";
}
else
{
$query1 = "exec updateRecord $Record,$Stat,$Tech,$Action,$Date,$time";
}
$ask = sqlsrv_query($conn, $query1);
sqlsrv_fetch($ask);
.........
?>
What am I forgetting....?
The server seems to return an empty response and the actual record is not updated.
got it to work:
$query1 = "EXEC updateRecord #Record = '$Record', #Status = '$Stat', #Tech = '$Tech', #Date = '$Date', #time = '$time', #Actions = '$Action'";
thanks to this: https://stackoverflow.com/a/44911709
I'm trying to get the registry id inserted in the database using MySQLi insert_id but it is giving error.
I already researched the web but found nothing that solved this problem.
Where am I going wrong?
<?php
date_default_timezone_set('America/Sao_Paulo');
$data = date('d-m-Y');
$hora = date('H:i:s');
$id_motorista = $_POST["id_motorista"];
$km = $_POST["km"];
$valor = $_POST["valor"];
$placa = $_POST["placa"];
$posto = $_POST["posto"];
$litros = $_POST["litros"];
$photo_user_origem = $_FILES["photo_user"]["tmp_name"];
$photo_user_destino = "photos/".md5(time()).".png";
$conn = new mysqli("localhost", "root", "", "banco");
$sql = "INSERT INTO abastecimentos (dia, km, posto, litros, placa, valor, id_motorista) VALUES ('$data','$km','$posto','$litros','$placa','$valor','$id_motorista')";
$stm = $conn->prepare($sql);
//ERROR SHOULD BE THERE STARTED HERE
if ($stm->execute()){
$id_bastecimento = $conn->insert_id;
$stm->close();
if (move_uploaded_file($photo_user_origem, $photo_user_destino)){
$sql_update_photo = 'UPDATE abastecimentos SET photo_usuario = ? WHERE id_bastecimento = ?';
$stm = $conn->prepare($sql_update_photo);
$stm->bind_param("si", $photo_user_destino, $id_bastecimento);
$stm->execute();
}
$retorno = array("retorno" => "YES");
} else {
$retorno = array("retorno" => "NO");
}
echo json_encode($retorno);
$stm->close();
$conn->close();
?>
I'm working with SQLite on my webserver and have had no problems until now.
$sql = "SELECT * from TeammateCurrent;";
$ret = $db->query($sql);
if($ret != false) {
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
$uniqueid = $row['uniqueID'];
$name = $row['Name'];
$lineID = $row['LineID'];
$job = $row['Job'];
$sunday = $row['Sunday'];
$monday = $row['Monday'];
$tuesday = $row['Tuesday'];
$wednesday = $row['Wednesday'];
$thursday = $row['Thursday'];
$friday = $row['Friday'];
$saturday = $row['Saturday'];
//echo $name."<br>".$lineID."<br>".$job."<br>".$sunday."<br>".$monday."<br>".$tuesday."<br>".$wednesday."<br>".$thursday."<br>".$friday."<br>".$saturday."<br><br>";
$sql = "INSERT INTO TeammateHistory (uniqueID, Name,LineID,Job,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday)
VALUES (NULL, '$name','$lineID','$job','$sunday','$monday','$tuesday','$wednesday','$thursday','$friday','$saturday');";
$ret = $db->exec($sql);
if(!$ret){
echo $db->lastErrorMsg();
} else {
}
$sql2 = "UPDATE TeammateCurrent set Sunday='$day0', Monday='$day1', Tuesday='$day2', Wednesday='$day3', Thursday='$day4', Friday='$day5', Saturday='$day6' where uniqueID='$uniqueid';";
$ret = $db->exec($sql2);
if(!$ret){
echo $db->lastErrorMsg();
} else {
}
}
} else {
echo "Query not successful";
}
When the code above executes, I get the error Fatal error: Call to a member function fetchArray() on a non-object in /home/xxxx/public_html/xxxx.com/trg/rc2/db/startNewWeek.php on line 39
I've ran code just like this on other pages and they work fine, I'm at a total loss here.
My tables:
you're reusing the variable $ret. You should have a different return variable for the SELECT statment and UPDATEs. In the second loop you're trying to do a fetchArray() of the return of an UPDATE statement.
At the end of this code there is a INSERT INTO statement that doesn't do anything. My connection.php is OK because I have used the same file in other projects and they work.
I am actually inserting a lot more data, but I was trying to find the problem out so I've removed a lot of variable from the INSERT statement.
<?php
include("connection.php");
include("functions.php");
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
date_default_timezone_set('Asia/Dhaka');
$mobile = (string)$_GET["mobile_number"];
$promo = (string)$_GET["promo_code"];
$type = (string)$_GET["type"];
$type_no = (($type=="imei") ? (string)$_GET["imei"] : (string)$_GET["udid"]);
$ip = (string)$_SERVER['REMOTE_ADDR'];
$signup_date = date("Y-m-d");
$q1 = "SELECT * FROM vbClient WHERE clCustomerID = :mobile";
$chk_mob_switch = $dbh->prepare($q1);
$chk_mob_switch->bindParam(':mobile', $mobile);
$chk_mob_switch->execute();
if ($chk_mob_switch->rowCount() == 0) {
$q2 = "SELECT * FROM api_db WHERE type_no = :type_no";
$chk_imei_bknd = $dbh->prepare($q2);
$chk_imei_bknd->bindParam(':type_no', $type_no);
$chk_imei_bknd->execute();
if ($chk_imei_bknd->rowCount() == 0) {
$validation_code = (string)generateValidationCode(6);
$request_id = (string)generateRequestID(15);
$q3 = "INSERT INTO api_db (mobile) VALUES (:mobile)";
$ins_info_bknd = $dbh->prepare($q3);
$ins_info_bknd->bindParam(':mobile', $mobile);
$ins_info_bknd->execute();
}
To check for errors I am using a function like the following:
function chkSyntax($dbh, $stmt, $query) {
$stmt = $dbh->prepare($query);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
}
And then I'm calling it like this:
chkSyntax($dbh, $chk_mob_switch, $q1);
What am I doing wrong?