Update query from PHP does not work - php

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().

Related

This script is too slow, any way to improve its performance?

This script is too slow, any way to improve its performance? The word is loaded by returning this function within the page, and fetching a table in the database.
The connection is via PDO and the MySQL database
function fnc_translate($texto) {
include("conn.php");
$lang['pt-br'] = 'PT_BR';
$lang['en'] = 'EN';
$lang['es'] = 'ES';
$lang['no'] = 'NO';
if(!isset($_GET['lang']) && !isset($_SESSION['lang'])){
$stmt = "SELECT LANG_PT_BR FROM LANG WHERE LANG_PT_BR=:texto";
$row_name = "LANG_PT_BR";
$_SESSION['lang'] = 'pt-br';
}elseif(!isset($_GET['lang']) && isset($_SESSION['lang'])){
$stmt = "SELECT LANG_".$lang[$_SESSION['lang']]." FROM LANG WHERE LANG_PT_BR=:texto";
$row_name = "LANG_".$lang[$_SESSION['lang']];
}elseif(isset($_GET['lang'])){
$stmt = "SELECT LANG_".$lang[$_GET['lang']]." FROM LANG WHERE LANG_PT_BR=:texto";
$row_name = "LANG_".$lang[$_GET['lang']];
$_SESSION['lang'] = $_GET['lang'];
}else{
$stmt = "SELECT LANG_PT_BR FROM LANG WHERE LANG_PT_BR=:texto";
$row_name = "LANG_PT_BR";
$lang = $_SESSION['lang'] = 'pt-br';
}
try {
$sql=$conn->prepare($stmt);
$sql->bindParam(':texto',$texto,PDO::PARAM_STR);
$sql->execute();
$row=$sql->fetch();
} catch (PDOException $e) {
return $texto = $texto;
}
if(isset($row[$row_name])){
return $texto = $row[$row_name];
}else{
return $texto = null;
}
}
My problem is solved! As you already imagined, the problem was not in the code above, but in the settings in the PHP.INI of the local server. I used the Cloud settings and the speed was normalized.

How can i update multiple table with one query php?

if($_SERVER['REQUEST_METHOD'] == 'POST'){
$content = file_get_contents('php://input');
$user = json_decode($content, true);
$id_a = $user['id_a'];
$id_b = $user['id_b'];
$aName = $user['aName'];
$bName = $user['bName'];
$sql = "
BEGIN TRANSACTION;
UPDATE `tb1`
SET `aName` = '$aName'
WHERE `id_a` = '$id_a';
UPDATE `tb2`
SET `bName` = '$nName'
WHERE `id_b` = '$id_b';
COMMIT
";
$result = $conn->query($sql);
if($result){
echo json_encode(['status'=>'success','message'=>'Edited successfully']);
}
else{
echo json_encode(['status'=>'error','message'=>'An error occurred editing the information.']);
}
}
else{
echo json_encode(['status'=>'error','message'=>'REQUEST_METHOD Error']);
}
$conn->close();
I need to update data multiple table but when i use above code it it response "Edited successfully" but in database data didn't change anything
but when update single table it can
No need for a transaction because it seems your PDO does not accept a transaction.
Something like this should work in the example you gave:
UPDATE tb1, tb2
SET tb1.aName = $aName,
tb2.bName = $bName
WHERE
tb1.id_a = $id_a
AND tb2.id_b = $id_b;

PHP doesn't execute functions with sql correct

I will put my code below. I basically check on value in the database and if it's 1 or 0 i want to change it to the opposite (so if 1 change it to 0, if 0 change to 1).
If I execute one SQL statement without using the function (but then it only works one way once) it works. But if I want to execute the specific function with it depending on what the value currently is, it doesn't seem to work. Do you know what I am doing wrong here?
<?php
$date_id = $_POST['dateID'];
$con = mysqli_connect("localhost","root","","secret_name");
$sql = "SELECT * FROM date_list WHERE date_id = ".$dateID;
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
$occupied = $row['occupied'];
if($occupied == 1){
decross_entry();
} elseif( $occupied == 0){
cross_entry();
}else{
echo "Error"
}
}
function decross_entry(){
$dateID = $_POST['dateID'];
$con_2 = mysqli_connect("localhost","root","","secret_name");
$sql_edit = "UPDATE date_list SET occupied= '0' WHERE date_id = ".$dateID;
if($con_2 -> connect_errno){
echo "Failed to connect to database!" . $con_2->connect_error;
}
if ($con_2 -> query($sql_edit) === TRUE)
{
echo "saved!";
} else {
echo "error: " .$sql_edit."<br>".$con_2->error;
}
}
function cross_entry(){
$dateID = $_POST['dateID'];
$con_2 = mysqli_connect("localhost","root","","secret_name");
$sql_edit = "UPDATE date_list SET occupied= '1' WHERE date_id = ".$dateID;
if($con_2 -> connect_errno){
echo "Failed to connect to database!" . $con_2->connect_error;
}
if ($con_2 -> query($sql_edit) === TRUE)
{
echo "saved!";
} else {
echo "error: " .$sql_edit."<br>".$con_2->error;
}
}
?>
If the only possible values of occupied are 0 and 1 then you can do what you want in one query without needing to look up the value of occupied first:
UPDATE date_list
SET occupied = 1 - occupied
WHERE date_id = ?
In PHP, using a prepared query to avoid SQL injection:
$date_id = $_POST['dateID'];
$con = mysqli_connect("localhost","root","","secret_name");
$sql = "UPDATE date_list SET occupied = 1 - occupied WHERE date_id = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param('i', $date_id); // use 's' if $date_id is not an integer
$stmt->execute();

Cant call stored procedure from PHP

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

How to properly update a SQL table row using PHP

Current update: I've cleaned up the code, and there are still some issues.
NOTE this code runs every 3 seconds. The outermost 'else' statement seems to run, setting the time to 0 in the database table, but then there is no activity.
After the initial time of running, the outermost 'else' statement should never run, and the time value stored under the user's alias should keep updating with the latest time stamp, but it just sits at '0'.
This is the JS that runs the php file:
//CHECK FOR NEW CHAT MESSAGES
setInterval(function()
{
$.post("chat_update.php", function(data) { $("#rect_comments_text").append(data);} );
}, 3000);
Code:
<?php
session_start();
$alias = $_SESSION['username'];
$host = 'localhost';
$user = '*';
$pass = '*';
$database = 'vethergen_db_accounts';
$table = 'table_messages';
$time_table = 'table_chat_sync';
$connection = mysqli_connect($host, $user, $pass) or die ("Unable to connect!");
mysqli_select_db($connection,$database) or die ("Unable to select database!");
$timestamp = time();
$last_time_query = "SELECT alias FROM $time_table";
$last_time_result = mysqli_query($connection,$last_time_query);
$last_time_rows = mysqli_fetch_array($last_time_result);
if ($last_time_rows['alias'] === $alias)
{
$last_time = $last_time_rows['time'];
$query = "SELECT * FROM $table WHERE time > $last_time ORDER BY text_id ASC"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
//APPEND NEW MESSAGES
while($row = mysqli_fetch_array($result))
{
if ($row['alias'] === "Vether")
{
echo '<p id = "chat_text">'.'<b>'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
else
{
echo '<p id = "chat_text">'.'<b class = "bold_green">'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
echo '<hr class = "chat_line"></hr>';
}
//UPDATE LAST SYNC TIME
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
else
{
echo '<p> HERE </p>';
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','0')";
mysqli_query($connection,$update_query);
}
?>
You try this
$sql_update = "UPDATE time_table SET time= '$timestamp' WHERE alias = '$alias'";
if ($con->query($sql_update ) === TRUE) {
}
else{
echo "Error: " . $sql_update . "<br>" . $con->error;
}
You need to only check mysqli_num_rows to whether to insert or update data. You have to add ' around $alias in select query also. change your code as below:
//EITHER UPDATE THE EXISTING VALUE OR CREATE ONE FOR FIRST TIME VISITORS...
$last_time_query = "SELECT * FROM $time_table WHERE alias = '$alias'"; //change here add '
$last_time_result = mysqli_query($connection,$last_time_query);
if (mysqli_num_rows($last_time_result) == 0) //Only check number of rows
{
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','$timestamp')";
mysqli_query($connection,$update_query);
}
else
{
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}

Categories