I
I
Ivan Vekov2018-03-20 14:01:03
PHP
Ivan Vekov, 2018-03-20 14:01:03

mssql_connect / PDO('sqlsrv'). How to make a command on UPDATE?

I need to write some data to a remote MSSQL server from PHP. For reading, everything works fine, but when you try to do an UPDATE, nothing happens. Does anyone have any ideas what could be the issue?

public static function set_finish_date($ID, $date)
  {
    if(function_exists('mssql_connect'))
    {
      $arResult['connection_type'] = 'mssql_connect';
      $connection = mssql_connect(self::$host, self::$user , self::$password);
      if ( !$connection ) {
        if ( function_exists('error_get_last') ) {
          var_dump(error_get_last());
        }
        $arResult['error'][] = 'connection failed';
      }
      $db = mssql_select_db(self::$database, $connection)
      or $arResult['error'][] = 'Не удалось выбрать БД';
      $result = mssql_query('UPDATE Pmark SET Finish='.$date.' WHERE ID='.$ID);
      if($result)
      {
        $arResult['success'] = true;		
      }
      else 
      {
        $arResult['error'] = 'Не удалось записать значение';	
      }
    }
    else 
    {
      $arResult['connection_type'] = 'PDO';
      #Соединение
      $db = new PDO("sqlsrv:Server=".self::$host.";Database=".self::$database, self::$user, self::$password);
      #Смена даты
      $stmt = $db->prepare('UPDATE Pmark SET Finish='.$date.' WHERE ID='.$ID);
      try{
        $stmt->execute();
        $arResult['success'] = "Успешно создана новая запись";
      }
      catch(PDOException $e) {
        $arResult['error'] = $e->getMessage();
      }
    }
    return CUtil::PhpToJSObject($arResult);		
  }

Returns:
{'connection_type':'PDO','error':'SQLSTATE[42000]: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Incorrect syntax near construction "00".'}
And from another server :
{'connection_type':'mssql_connect','error':'Failed to write value'}
------------After solving the problem-------------- ------
The original problem was the lack of quotes before the date, rewrote it like this:
$stmt = $db->prepare("UPDATE Pmark SET Finish='".$date."' WHERE ID='".$ID. "'");
The second problem was in date formats for MSSQL. Between the date and time it was necessary to put the letter "T" (Latin) instead of a space.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lazy @BojackHorseman PHP, 2018-03-20
@vekov

datetime (Transact-SQL)
pass date to query in format that ms sql supports

F
FanatPHP, 2018-03-20
@FanatPHP

Before using the tool, you should at least look at examples of working with it
$db = new PDO("sqlsrv:Server=".self::$host.";Database=".self::$database, self::$ user,self::$password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->prepare('UPDATE Pmark SET Finish=? WHERE ID=?')->execute([$date, $id]);
$arResult['success'] = true;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question