0

I have a string that contain a mysql query:

$string = "UPDATE [table1] SET value = 1 WHERE id = 1";

I would like to change [table1] with the value of this array:

$table['table1']='pages';
$table['table2']='products';
etc

The result should be:

mysql_query( $string ); // "UPDATE pages SET value = 1 WHERE id = 1"

I already tried the following but nothing:

mysql_query( str_replace( '[', '$table[', $string ));
mysql_query( str_replace( array_keys( "[$table]" ), array_values( $table ), $string ));
mysql_query( str_replace( array_keys( "[".$table."]" ), array_values( $table ), $string ));

EDIT This way works, but there is no a easiest way?

str_replace( explode( ',', ( '['.implode( '],[',array_keys( $table ) ) .']' ) ), $table, $string );

2 Answers 2

1

What about this

$table['table1']='pages';
$table['table2']='products';

$string = "UPDATE [table1] SET value = 1 WHERE id = 1";

foreach($table as $key => $value){
    $string = str_replace('['.$key.']', $value, $string);
}
Sign up to request clarification or add additional context in comments.

Comments

0

What about the simple approach?

$string = "UPDATE ".$table['table1']." SET value = 1 WHERE id = 1";

1 Comment

No I cannot do that, I have to convert the [table1] with the value of $table[table1]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.