2010-10-05 7 views
12
$test = sprintf("SELECT * FROM `table` WHERE `text` LIKE '%%s%'", mysql_real_escape_string('test')); 

echo $test; 

uscita:MySQL COME + PHP sprintf

SELECT * FROM `table` WHERE `text` LIKE '%s 

ma dovrebbe uscita:

SELECT * FROM `table` WHERE `text` LIKE '%test%' 

risposta

34
... LIKE '%%%s%%'", mysql_real_escape_string('test')); 

Per stampare il carattere % hai bisogno di fuggire con sé. Pertanto i primi due %% stamperanno il carattere %, mentre il terzo è per lo specificatore di tipo %s. Hai bisogno anche di un doppio %% alla fine.

+0

La ringrazio . Questo mi ha aiutato. –

3

Prova:

$test = sprintf("SELECT * FROM `table` WHERE `text` LIKE '%%%s%%'", mysql_real_escape_string('test')); 

In sprintf, se si vuole ottenere un segno %, è necessario inserire %%. Quindi è %% per la prima wildcard %, %s per la stringa stessa e %% per l'ultimo carattere jolly %.

0
$test = "SELECT * FROM `table` WHERE `text` LIKE '%s%'" . mysql_real_escape_string('test'); 

echo $test; 
1

È necessario evitare i segni di percentuale con un segno di percentuale %%.

$test = sprintf("SELECT * FROM `table` WHERE `text` LIKE '%%%s%%'", mysql_real_escape_string('test')); 

echo $test; 
1

Sei contesti jumbling. Per coerenza, mettere le cose che non sono all'interno del SQL singole citazioni al di fuori della sprintf() stringa di formato:

$test = sprintf(
      "SELECT * FROM `table` WHERE" 
      . "`xt` LIKE '%s'", 
      "%" . mysql_real_escape_string("test") . "%" 
     );