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
Related
I used localhost and everything works fine, however, when I hosted it in digital ocean, certain POST functions don't write to the mysql database.
I've tried using Postman to test the code, and it returns 200 OK and error writing to database.
My db_functions code:
public function insertNewListing($name,$imgPath,$price,$listingId,$descriptions,$packageOne,$packageTwo,$moreDescriptions,$itinerary,$imgPathTwo,$imgPathThree)
{
$stmt= $this->conn->prepare("INSERT INTO `Longhouses`(`Name`, `Link`,`Price`,`ListingId`,`descriptions`,`PackageOne`,`PackageTwo`,`MoreDescription`,`Itinerary`,`ImageTwo`,`ImageThree`) VALUES (?,?,?,?,?,?,?,?,?,?,?)") or die ($this->conn->error);
$stmt->bind_param("sssssssssss",$name,$imgPath,$price,$listingId,$descriptions,$packageOne,$packageTwo,$moreDescriptions,$itinerary,$imgPathTwo,$imgPathThree);
$result = $stmt->execute();
$stmt->close();
if($result)
return true;
else
return false;
}
My add_listing function:
<?php
require_once '../../db_functions.php';
$db = new DB_Functions();
if(isset($_POST['name'])&&isset($_POST['imgPath'])&&isset($_POST['price'])&&isset($_POST['listingId'])&&isset($_POST['descriptions'])&&isset($_POST['packageOne'])&& isset($_POST['packageTwo'])&&isset($_POST['moreDescriptions'])&& isset($_POST['itinerary'])&& isset($_POST['imgPathTwo'])&& isset($_POST['imgPathThree']))
{
$name = $_POST['name'];
$imgPath = $_POST['imgPath'];
$price = $_POST['price'];
$listingId = $_POST['listingId'];
$descriptions = $_POST['descriptions'];
$packageOne = $_POST['packageOne'];
$packageTwo = $_POST['packageTwo'];
$moreDescriptions = $_POST['moreDescriptions'];
$itinerary = $_POST['itinerary'];
$imgPathTwo = $_POST['imgPathTwo'];
$imgPathThree = $_POST['imgPathThree'];
$result = $db->insertNewListing($name,$imgPath,$price,$listingId,$descriptions,$packageOne,$packageTwo,$moreDescriptions,$itinerary,$imgPathTwo,$imgPathThree);
if($result)
echo json_encode("ADD LISTING SUCCESFUL");
else
echo json_encode("error writing to database");
}
I run this update query from PHP code:
$update_begin_insurance = "UPDATE `vehicles`
SET `begin_insurance_date` = '$begin_insurance'
WHERE `plate` = '$plate'";
$conn->query($update_begin_insurance);
$conn is a PDO object.
The problem is that any exception is thrown by $conn, but the vehicles table in my database is not updated. So, I've tried to run this query directly through phpmyadmin, and it works correctly, so I think it's a PHP problem, but I can't figure out where the problem is.
My begin_insurance_date column is of type DATE, and $begin_insurance is a string in the correct format (YYYY-MM-DD, I've tried this code with 2017-06-10).
I'm using MySQL DBMS
This is the echo of $update_begin_insurance:
UPDATE `vehicles`
SET `begin_insurance_date` = '2017-06-10'
WHERE `plate` = 'ccccc'
UPDATE
This is the full PHP code of my page:
<?php
require_once "connect_db.php";
$plate = $_POST["plate"];
$begin_insurance = $_POST["begin_insurance"];
$end_insurance = $_POST["end_insurance"];
$fuel_economy = $_POST["fuel_economy"];
$fuel_type = $_POST["fuel_type"];
$response = array();
try
{
$conn->beginTransaction();
if ($begin_insurance != "")
{
$update_begin_insurance = "UPDATE `vehicles`
SET `begin_insurance_date` = '$begin_insurance'
WHERE `plate` = '$plate'";
$conn->query($update_begin_insurance);
}
if ($end_insurance != "")
{
$update_end_insurance = "UPDATE `vehicles`
SET `end_insurance_date` = '$end_insurance'
WHERE `plate` = '$plate'";
$conn->query($update_end_insurance);
}
if ($fuel_economy != "")
{
$update_fuel_economy = "UPDATE `vehicles`
SET `fuel_economy` = $fuel_economy
WHERE `plate` = '$plate'";
$conn->query($update_fuel_economy);
}
if ($fuel_type != "")
{
$update_fuel_type = "UPDATE `vehicles`
SET `id_fuel` = $fuel_type
WHERE `plate` = '$plate'";
$conn->query($update_fuel_type);
}
$response["post"] = $_POST;
$response["error_code"] = "0";
$response["error_message"] = "none";
$response["driver_error_code"] = "0";
}
catch (PDOException $e)
{
if ($conn->inTransaction())
{
$conn->rollBack();
}
$response["post"] = $_POST;
$response["error_code"] = $e->getCode();
$response["error_message"] = $e->getMessage();
$response["driver_error_code"] = $e->errorInfo[1];
}
echo json_encode($response);
?>
As I said before, I don't get any exception (as you can see, I also print the $_POST array to check if the params are received correctly, and yes, they are).
This is what echo json_encode($response) prints:
{
"post":
{
"plate":"ccccc",
"begin_insurance":"2017-06-10"
},
"error_code":"0",
"error_message":"none",
"driver_error_code":"0"
}
I'm sure the connection works correctly because I've got others PHP files which execute some INSERT queries, and they works correctly.
I've solved the problem, I was missing the $conn->commit().
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 making a form for some project. The problem is when the user enter their data using the field and then submit, the input not keep in the database.
Also when clicking submit the direct page show blank empty page even the connection test also not showing.
I'm using almost similar code for other project and it work except for this.
below is my code:
<?php
//check connection
require 'config.php';
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
//asas (table name)
$id = $_POST["Sid"]; $ic = $_POST["Sic"];
$name = $_POST["Snp"]; $jant = $_POST["J1"];
$trum = $_POST["Chr"];$tbim = $_POST["Chp"];
$mel = $_POST["Sem"]; $arum = $_POST["Ar"];
$asum = $_POST["As"];
//institusi
$thp = $_POST["T1"]; $uni = $_POST["Sis"];
$bid = $_POST["tpe"];$Aint = $_POST["Ai"];
//industri
$bip = $_POST["bid"];$bik = $_POST["B1"];
$tem = $_POST["te"];$mula = $_POST["tm"];
$tamm = $_POST["tt"]; $res = $_POST["fileToUpload1"];
$tran = $_POST["fileToUpload2"];$keb = $_POST["fileToUpload3"];
$link = mysqli_connect($h,$u,$p,$db);
if('id' != '$Sid'){
$asas = "insert into asas Values ('$id','$ic','$name','$jant','$trum','$tbim','$mel','$arum','$asum')";
$inst = "insert into institusi Values ('$thp','$uni','$bid','$Aint')";
$indr = "insert into industri Values ('$bip','$bik','$tem','$mula','$tamm','$res','$tran','$keb')";
mysqli_query($link,$asas);
mysqli_query($link,$inst);
mysqli_query($link,$indr);
mysqli_close($link);
}
else
{
echo "failed"
}
?>
<b>Register complete</b>
Can anybody tell me what the error or maybe some solution. Thanks
I think you are having problem in insert query, please check this:
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
Write this kind.
thank you
there are few issues with the code like variable id was used without $
and need to use die method with mysqli_query() function to check for
errors, please check below improved codes, it may help you -
<?php
//check connection
require 'config.php';
if (isset($_POST)) {
//asas (table name)
$id = $_POST["Sid"];
$ic = $_POST["Sic"];
$name = $_POST["Snp"];
$jant = $_POST["J1"];
$trum = $_POST["Chr"];
$tbim = $_POST["Chp"];
$mel = $_POST["Sem"];
$arum = $_POST["Ar"];
$asum = $_POST["As"];
//institusi
$thp = $_POST["T1"];
$uni = $_POST["Sis"];
$bid = $_POST["tpe"];
$Aint = $_POST["Ai"];
//industri
$bip = $_POST["bid"];
$bik = $_POST["B1"];
$tem = $_POST["te"];
$mula = $_POST["tm"];
$tamm = $_POST["tt"];
$res = $_POST["fileToUpload1"];
$tran = $_POST["fileToUpload2"];
$keb = $_POST["fileToUpload3"];
}
$link = mysqli_connect($h, $u, $p, $db);
if (!$link) {
die("Connection failed: " . mysqli_connect_error());
}
// if('id' != '$Sid'){
if ($id != '$Sid') {
$asas = "insert into asas Values
('$id','$ic','$name','$jant','$trum','$tbim','$mel','$arum','$asum')";
$inst = "insert into institusi Values ('$thp','$uni','$bid','$Aint')";
$indr = "insert into industri Values
('$bip','$bik','$tem','$mula','$tamm','$res','$tran','$keb')";
if (mysqli_query($link, $asas)) {
echo "records inserted";
} else {
echo "failed".mysqli_error($link) ;
}
if (mysqli_query($link, $inst)) {
echo "records inserted";
} else {
echo "failed".mysqli_error($link) ;
}
if (mysqli_query($link, $indr)) {
echo "records inserted";
} else {
echo "failed".mysqli_error($link) ;
}
}
mysqli_close($link);
?>
<b>Register complete</b>
just use or die after mysqli_query
mysqli_query($link,$asas)or die ('Unable to execute query. '. mysqli_error($link));
you will get to know what is the actual problem
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?