Updating table with form using PHP to MS SQL - php

I am struggling trying to update a row in an Azure SQL database.
What I am trying to do is to update a row with some input variables along with a fresh datestamp.
If I input the following (for test purposes), my database is updated, but the date is way off:
"UPDATE TABLENAME set COL1 = ".$_POST[VAL1].", COL2 = ".$_POST[VAL2].", COL3 = 2020-03-20 WHERE COL0 = 'VAL0'"
giving me a datestamp looking like this: 1905-06-21T00:00:00.0000000
I have been trying just around a hundred ways of formatting the date() variable, putting it in my SQL statement like this:
"UPDATE TABLENAME set COL1 = ".$_POST[VAL1].", COL2 = ".$_POST[VAL2].", COL3 = ".date()." WHERE COL0 = 'VAL0'"
Needless to say, COL3 is my datestamp column. But I cannot get the database to accept my datestamp formatting. I have tried YYYY-mm-dd xyz1234 in countless variants inside date(), but to no avail.
The database has the following collation set: SQL_Latin1_General_CP1_CI_AS.
Any pointers?

First, about your incorrect date value. It is correct, because when you miss '' around 2020-03-20, SQL Server makes implicit data type conversion. Next example demonstrates this:
Implicit conversion:
DECLARE #date datetime
SELECT #date = 2020-03-20
SELECT #date
SELECT DATEADD(day, 2020-03-20, 0)
Output:
1905-06-21 00:00:00.000
Second, if you want to pass date and time values, just use appropriate format - 'yyyy-MM-dd', 'yyyyMMdd hh:nn:ss' or 'yyyy-MM-ddThh:nn:ss':
"UPDATE TABLENAME set COL1 = ".$_POST[VAL1].", COL2 = ".$_POST[VAL2].", COL3 = '2020-03-20' WHERE COL0 = 'VAL0'"
I don't know how you make your connection to SQL Server, but try to use prepared statements.
Update (Retrieve and send date and time values from and to SQL Server):
Based on driver that you use to connect to SQL Server, you may retrieve date and time values as text or as PHP datetime object (if you use PHP Driver for SQL Server), but you need to send these values as text. In your case values are returned as text. So you need to generate universal datetime value (in 'yyyy-MM-ddThh:nn:ss' for example) as text.
Next example shows some valid and invalid combinations for UPDATE T-SQL statement for your datetime column. It is tested with PHP Driver for SQL Server 4.0.3.
<?php
# Value from database as text
$row['COL3'] = '2019-03-29T11:35:30.0000000';
# Valid statement
$tsql = "UPDATE TABLENAME SET COL3 = '".substr($row['COL3'], 0, 19)."' ";
# Valid statement - date("Y-m-d\Th:i:s") will return current datetime
$tsql = "UPDATE TABLENAME SET COL3 = '".date("Y-m-d\Th:i:s")."' ";
# Invalid statement - date("d-m-Y h:i:s", $row['COL3']) expects int as second parameter,
# generates warning and returns '01-01-1970 12:33:39' as result
$tsql = "UPDATE TABLENAME SET COL3 = '".date("d-m-Y h:i:s", $row['COL3'])."' ";
?>

Related

PHP oci_fetch_all from an Oracle DB converts date value

I'm having issues getting a value from an Oracle DB where the value is converted to a date format I don't want. I'd prefer to have the raw value, or at least know where I can change that converted date format. Curious if anyone could point me in the right direction here.
$conn = oci_connect(ORACLE_DB_USERNAME, ORACLE_DB_PASSWORD, '//' . ORACLE_DB_HOST . '/' . ORACLE_DB_SID);
$sql_query = "SELECT * FROM \"ASSET\".\"NAV\" WHERE sem = '2820' AND ROWNUM = 1 ORDER BY date_time DESC";
$stid = oci_parse($conn, $sql_query);
$row_count = oci_fetch_all($stid, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW + OCI_ASSOC);
oci_free_statement($stid);
oci_close($conn);
The data in the DB should come back like:
CREATE_DATE => '23-07-2019 19:30:11'
Except, I get this:
CREATE_DATE => '23-JUL-19'
You are getting dates back in the default format of your database. One thing that you could to is alter the NLS setting of your session to the format that you expect. For this, you can run this command:
alter session set nls_date_format = 'dd-mm-yyyy hh24:mi:ss'
Once this command is executed, all dates will be fetched in this format during the lifetime of your Oracle session.
If you are dealing with timestamp datatype instead of date, then the nls parameter is nls_timestamp_format (and nls_timestamp_tz_format for timestamp with timezone).
Another option is to use to_char() to format the date to the desired format in the query itself:
$sql_query = "SELECT <column list>, to_char(create_date, 'dd-mm-yyyy hh24:mi:ss') create_date FROM ...";

Call Stored Procedure to Update table with Parameters PHP MySQL

Calling SELECT Statements with parameters is great and makes life coding so tidy. My problem comes to when I want to update data in the database using an UPDATE statement.
I have the Stored Proc with the UPDATE statement included, similar to this below
CREATE DEFINER = 'myuser'#'%'
PROCEDURE sp_upd_planning (
IN prop_id int(11),
IN planned_date varchar(15),
IN time_slot int(11),
IN by_who int(11),
IN cost decimal(15,2),
IN complete_date varchar(15),
IN lastupd_user varchar(100))
BEGIN
UPDATE planning
SET
Status = CASE
WHEN CompleteDate IS NOT NULL THEN 4
WHEN PlannedDate IS NULL THEN 2
WHEN PlannedDate IS NULL AND CompleteDate IS NULL THEN 3
END
,PlannedDate = planned_date
,BookingDate = NOW()
,TimeSlot = time_slot
,ByWho = by_who
,Cost = epc_cost
,Complete = CASE WHEN CompleteDate IS NOT NULL THEN 1 ELSE 0 END
,CompleteDate = complete_date
,LastUpdateDate = NOW()
,LastUpdateUser = lastupd_user
WHERE PropID = prop_id;
END
The statement works as should when I run the CALL sp_upd_planning(paramters here); within the database.
I'm using as a submit from a form, I've posted the relevant fields into variables and in my connection I call the Stored Proc again and as before in the database I use the variables to match the parameters needed like this (yes I know it's using mysql_ but I wanted to test quickly so I used this)
mysql_query("CALL sp_upd_planning('$planned', '$timeslot', '$bywho', '$cost', '$completed', '$inputby', $propid)") or die(mysql_error());
When the code executes all looks good and no errors and the main form submits as should with the jquery I set up, but when I check the database nothing is updated.
Why would this be?
It sounds like you aren't executing your statement. In PHP you still have to execute the statement after creation. Also if I remember correctly it is more secure to bind your parameters instead of pass them in the string. Try something like this:
$conn = new mysqli("mysql:host=$host;dbname=$dbname", $username, $password);
// execute the stored procedure
$sql = "CALL sp_upd_planning(:planned, :timeslot, :bywho, :cost, :completed, :inputby, :propid)";
$stmt = $conn->prepare($sql);
$stmt->bindParam('datatypes', $planned, $timeslot, $bywho, $cost, $completed, $inputby, $propid);
$stmt->execute();
Basically by the term datatypes lets assume the planned is a string, timeslot is a date/time, bywho is a string, cost is an int, completed is an int, inputby is a string, and propid is an int then it would say 'sdsiisi'

Naming a database table with the current date through PHP

I'm looking to run a mysql_query() that allows me to create a new table within a database and name it according to the current date and time.
Example: Create a table named 2012-01-09-03-00-00, or something along those lines.
I know that this is not an optimal way of doing things, but ultimately I'm going to take the data on this table and dump it into a bigger database.
I've tried the code:
<?php
$date = date('YmdHis', time()-(3600*5));
$exportSQL = "CREATE TABLE $date(
FirstName varchar(15)
)";
mysql_select_db($database);
mysql_query($exportSQL) or die (mysql_error());
echo "Table created!";
?>
But this has been to no good. Please Help and thanks in advance.
EDIT: THIS HAS BEEN SOLVED. THE CODE WORKING SHOULD LOOK LIKE THIS:
<?php
$date = date('YmdHis', time()-(3600*5));
$exportSQL = "CREATE TABLE `$date`(
FirstName varchar(15)
)";
mysql_select_db($database);
mysql_query($exportSQL) or die (mysql_error());
echo "Table created!";
?>
Except that it is very weird design, if you want to name table in such a way - place its name in square brackets, like this:
CREATE TABLE [2012-01-09 12:20:15.010] (your columns)
that means that you should have the name of the table BEFORE composing the query, OR you have to use dynamic sql like this:
DECLARE #sql NVARCHAR(MAX)
SET #sql = N'CREATE TABLE['+
CAST(DATEPART(year, GETDATE()) AS NVARCHAR)+N'-'+
CAST(DATEPART(month, GETDATE()) AS NVARCHAR)+N'-'+
CAST(DATEPART(day, GETDATE()) AS NVARCHAR)+N'-'+
CAST(DATEPART(hour, GETDATE()) AS NVARCHAR)+N'-'+
CAST(DATEPART(minute, GETDATE()) AS NVARCHAR)+N'-'+
CAST(DATEPART(second, GETDATE()) AS NVARCHAR)+
N'] (FirstName varchar(15))'
EXEC(#sql)
The presented syntax is for sql server, so due to the sql compliance you can replace square brackets with double quotes and use proper date functions, but the approach left just the same

Update int in MySQL Field

How can I increment an int in a cell of a MySQL database? I know that auto-increment is no use because I never want to add a new row, just update an existing one. I'm currently using this (POST var used for clarify, is verified in the real code):
$columnToUpdate = 'type'.$_POST['voteid'];
$query = "UPDATE myTable $columnToUpdate = $columnToUpdate+1 WHERE id=1;";
if(!mysql_query($query)) {
echo json_encode(array('success' => false, 'message' => 'Update failed: '.mysql_error()));
exit;
}
In the database I have 6 fields, id, type1, type2, type3, type4, type5, and a single row with id set to 1. The intention is to recieve a number (1-5), and build a reference to the correct column before updating the field. That results in Update failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=type4+1 WHERE id=1' at line 1, so I guess it's not getting the field value out properly before it increments.
Once this is working I'm also going to need to decrement a field in the same way, unless its value is 0. So for bonus points, can I do all this in one query or would it be better to split it up?
I think you've missed the keyword 'SET' from your query - try
$query = "UPDATE myTable SET $columnToUpdate = $columnToUpdate+1 WHERE id=1;";
Edit:
To do the "decrement unless it's zero" you could use something like:
UPDATE myTable SET $columnToUpdate =
CASE $columnToUpdate
WHEN 0 THEN 0
ELSE $columnToUpdate - 1
END CASE
WHERE id=1;`
For bonus points, to decrement:
$query = "UPDATE myTable SET '$columnToUpdate' = '$columnToUpdate'-1 WHERE id=1 AND '$columnToUpdate' > 0";
Besides the injection issues, it seems as if your workflow may need some work. Are you sure you want to choose the column that will be updated based on POST variable? It seems like you would specify the column and use the variable to find the record that needs to be updated:
IE:
"UPDATE myTable SET votes=votes+1 WHERE id=$post_variable;"
Again you should send the variable as a parameterized query to protect yourself from SQL injection.

PHP+MySQL Update TimeStamp and get NOW() back

Is it possible to merge these two mysql queries into one? I want to get NOW() returned to a php variable.
mysql_query('INSERT INTO translate (IDRef, RefType, Lang, Text, LastChangeTS) VALUES ('.$id.', \''.$reftype.'\', \''.$lang.'\', \''.$text.'\', NOW()) ON DUPLICATE KEY UPDATE text = \''.$text.'\', LastChangeTS = NOW()');
mysql_query('SELECT LastChangeTS FROM translate WHERE IDRef = '.$id.' AND RefType = \''.$reftype.'\' AND Lang = \''.$lang.'\'');
You can't merge a insert statement and a select statement. But, you can sure use a stored procedure which inserts the data and then returns the LastChange value.

Categories