de.comp.lang.php.* FAQ

19.3. String-Quoting bei Sybase

Antwort von Timm Friebe

Bei Sybase müssen Anführungsstriche Strings innerhalb von Queries nicht mit einem Backslash (\), sondern mit dem jeweils gleichen Zeichen escaped werden. Folgendes Beispiel sollte das anschaulich machen:

select "Er sagte: ""Hallo Welt"""
select 'Das gibt''s doch nicht'

Eine Komfort-Funktion, die sich darum kümmert, dass in SQL-Statements immer richtig gequotet wird, soll hier gezeigt werden:

function sybase_prepare() {
  $args= func_get_args();
  $sql= $args[0];
  if (sizeof($args)<= 1) return $sql;
  $j= 0;    
  $sql= $tok= strtok($sql, '%');
  while (++$j && $tok= strtok('%')) {
    $arg= (is_object($args[$j]) && method_exists($args[$j], 'toString') 
      ? $args[$j]->toString()
      : $args[$j]
    );
    switch ($tok{0}) {
      case 'd': 
        $sql.= ($arg === NULL ? 'NULL' : intval($arg)).substr($tok, 1); 
        break;
        
      case 'c': 
        $sql.= substr($tok, 1); 
        break;
        
      case 's': 
        $sql.= ($arg === NULL ? 'NULL' : "'".str_replace("'", "''", $arg)."'").substr($tok, 1); 
        break;
        
      default: 
        $sql.= '%'.$tok; $j--;
    }
  }
  return $sql;
}

// Beispiel 1
$sql= sybase_prepare('
  insert into person (
    person_id, name, company
  ) values (
    %d, %s, %s
  )',
  1,
  'Dau Jones',
  NULL
);

// Beispiel 2
class Date {
  var $utime;
  
  function Date($utime) {
    $this->utime= $utime;
  }
  
  function toString($fmt= 'Y-m-d H:i:s') {
    return date($fmt, $this->utime);
  }
}

$date= &new Date(time());
$sql= sybase_prepare(
  'select count(*) from %c where lastchange= %s',
  'account',
  $date
);

Antwort von Kerry W. Lothrop

Durch das Einschalten des Parameters magic_quotes_sybase ändert sich auch das Verhalten der Funktion addslashes() , selbst wenn die Parameter magic_quotes_gpc und magic_quotes_runtime deaktiviert sind.

$string = '\' \ "';

// magic_quotes_sybase = Off
echo addslashes($string);
Ergibt \' \\ \"

// magic_quotes_sybase = On
echo addslashes($string);
Ergibt '' \ "

Valid HTML 4.01! Valid CSS!

19.3. String-Quoting bei Sybase
http://www.php-faq.de/q/q-sybase-quoting.html
de.comp.lang.php.* FAQ | (c) Copyright 2000-2007 Das dclp-FAQ-Team