Daniel Daniel - 5 months ago 8
PHP Question

How to assign variable inside of the string in php?

I wanna store sql query in XML and execute it by php.

the problem is that i need to assign variable inside of string from XML but i don't know how to do this.

here is example.

XML

<data>
<test> select * from table where testdata = $testdata;
</test>
</data>


.

PHP

$xml_string = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/data.xml');
$xml = simplexml_load_string($xml_string);

$sql = $xml->test;

//here is the problem. variable $testdata is not recognized in the string
$testdata = "test";

$result = $this->conn->query($sql);

$data = $result->fetch_assoc();


can anyone let me know how to fix the problem? and i am also open to new suggestion to store or handle sql queries thanks.

Answer

Try this:

<data>
    <test> select * from table where testdata = '%s';
    </test>
</data>

Then:

$result = $this->conn->query(sprintf($sql, 'test'));    
$data = $result->fetch_assoc();