sql >> Database >  >> RDS >> Mysql

Voer met PHP de waarde uit van een variabele of een vooraf gedefinieerde CONSTANT uit een MySQL-resultaatreeks

Misschien als je de DB-strings opslaat in sprint_f formaat, ik zie geen andere manier:

$color = 'blue';
define('GRASS_COLOR', 'green');

$text = 'The sky is %s and the grass is %s';
$text = sprintf( $text, $color , GRASS_COLOR );

echo $text;

UPDATE

Blijkbaar was ik iets te haastig met de constatering 'ik zie geen andere manier '. Eigenlijk is dit zeker haalbaar met het gebruik van get_defined_vars() en get_defined_constants() functies. Het idee is om alle door de gebruiker gedefinieerde variabelen en constanten te verzamelen en die vervolgens in een string te vervangen. Dit kan zelfs een eenvoudige sjabloon-engine zijn (als deze nog niet bestaat).

// place here value from database
$text = 'The sky is $color and</br> the grass is GRASS_COLOR';

$color = 'blue';
define('GRASS_COLOR', 'green');

// collect all defined variables and filter them to get only variables of string and numeric type
$values = array_filter( get_defined_vars(), function( $item ) {
    return is_string($item) || is_numeric($item);
});

// append the dollar sign to keys
$keys = array_map( function( $item ) { 
    return '$'.$item;
}, array_keys( $values ) );

// create the final array by comining the arrays $keys and $values
$vars = array_combine( $keys, array_values( $values ) );

// relpace names of the variables with values
$text = str_replace( array_keys( $vars ), array_values( $vars ), $text );

// collect all constants and replace user defined constants with values
$constants = get_defined_constants( true );
$text = str_replace( array_keys( $constants['user'] ), array_values( $constants['user'] ), $text );

// we are done
echo $text;


  1. Hoe kan ik AND's en OR's combineren in mijn SQL-statement?

  2. Beperking van externe sleutels kan cycli of meerdere cascadepaden veroorzaken?

  3. DROP TABEL INDIEN BESTAAT Voorbeeld in PostgreSQL

  4. Hoe array json_encode met Franse accenten?