Error in MySQLi insert_id - php

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();
?>

Related

PHP pdo query insert twice sometime

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;
}
}
?>

SQLSRV bind param thats in mysql

I'm trying to convert this mysql code to work using sqlsrv
$planeId = $_GET["pid"];
$conn = OpenCon();
$sql = "SELECT id, pid, fullname, tat, date, engine1, engine2, engine3, engine4 FROM oil WHERE pid = ? order by date desc";
$stmnt = $conn->prepare($sql);
$stmnt->bind_param("s", $planeId);
$stmnt->bind_result($id, $pid, $fullname, $tat, $date, $engine1, $engine2, $engine3, $engine4);
$stmnt->execute();
$theRows = Array();
while ( $stmnt->fetch() )
{
$aRow['id'] = "$id";
$aRow['pid'] = "$pid";
$aRow['fullname'] = $fullname;
$aRow['tat'] = $tat;
$aRow['date'] = $date;
$aRow['engine1'] = $engine1;
$aRow['engine2'] = $engine2;
$aRow['engine3'] = $engine3;
$aRow['engine4'] = $engine4;
$theRows[] = $aRow;
}
$stmnt->close();
echo json_encode($theRows);
CloseCon($conn);
This I what I've done so far but I'm missing the bind-param function not sure how to implement that. Because the output keeps coming out like this
[{"id":"","pid":"","fullname":null,"tat":null,"date":null,"engine1":null,"engine2":null,"engine3":null,"engine4":null}]
Even though I know there's an entry in Microsoft DB
$planeId = $_GET["pid"];
$theRows = Array();
$conn = OpenCon();
$query = "SELECT id, pid, fullname, tat, date, engine1, engine2, engine3, engine4 FROM oil WHERE pid = ? order by date desc";
//$stmnt = $conn->prepare($query);
$stmnt = sqlsrv_prepare($conn, $query, array(&$planeId));
if (sqlsrv_execute($stmnt) === false){
die( print_r( sqlsrv_errors(), true));
}
else{
while ( sqlsrv_fetch($stmnt) )
{
$aRow['id'] = "$id";
$aRow['pid'] = "$pid";
$aRow['fullname'] = $fullname;
$aRow['tat'] = $tat;
$aRow['date'] = $date;
$aRow['engine1'] = $engine1;
$aRow['engine2'] = $engine2;
$aRow['engine3'] = $engine3;
$aRow['engine4'] = $engine4;
$theRows[] = $aRow;
}
echo json_encode($theRows);
}
CloseCon($conn);

After conversion to PDO data is not displayed at ListView

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);

PHP PDO Insert Into statement doesn't work with no errors

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?

Error: You have an error in your SQL syntax near '' at line 1

I keep getting this error...but yet I cannot see any syntax that is inappropriate... any ideas?
Here's my PHP code. I know my other pages are correct as I can run all other parts of the code with no issue.
<?php
// this connects To database
$hostname="";
$username="";
$password="";
$dbname="";
mysql_connect($hostname,$username,$password) OR DIE ("Connection Failed");
mysql_select_db($dbname);
$action = $_REQUEST["action"];
if ($action == 'a') {
$custFirst = null;
$custLast = null;
$custAddress = null;
$custCity = null;
$custState = null;
$custZip = null;
$custEmail = null;
$custPhone = null;
} else {
$id = $_REQUEST["id"];
$query = "select * from custTab where custNo = $id";
$result = mysql_query($query)
or die(mysql_error());
$row = mysql_fetch_array($result);
$custFirst = $row['custFirst'];
$custLast = $row['custLast'];
$custAddress = $row['custAddress'];
$custCity = $row['custCity'];
$custState = $row['custState'];
$custZip = $row['custZip'];
$custEmail = $row['custEmail'];
$custPhone = $row['custPhone'];
} // end if
?>
Try putting quotes around the $id,
$query = "select * from custTab where custNo = '$id'";
This is dangerous and wrong depending on what the custNo field contains:
$id = $_REQUEST["id"];
$query = "select * from custTab where custNo = $id";
If the id is an integer, you should use:
$id = (int) $_REQUEST["id"];
$query = "select * from custTab where custNo = $id";
Otherwise you would have to quote it and escape the variable:
$id = mysql_real_escape_string($_REQUEST["id"]);
$query = "select * from custTab where custNo = '$id'";
But you really should switch to PDO / mysqli and prepared statements to avoid this problem altogether.

Categories