I am trying to enable foreign key constraint of sqlite database from my php script.
I tried :
shell_exec('sqlite ex.db');
shell_exec('PRAGMA foreign_keys = ON');
echo $isEnabled = shell_exec('PRAGMA foreign_keys');
But I am not getting $isEnabled
as 1
. In fact I am not getting anything as output.
Thanks.
Why you dont use the built-in SQLite driver?
$con = new SQLite3('ex.db');
$con->exec('PRAGMA foreign_keys = ON;');
var_dump($con->query('PRAGMA foreign_keys;')->fetchArray());
According your problem: shell_exec()
(as the name suggest) executes shell commands. This means, that you try to execute three (!) shell commands, but you want to execute one and then you want to execute 2 more commands within the interactive sqlite3-process you started before. This is not possible this way. Maybe you can play around with stdin
, but because PHP comes with SQLite3-support I don't see a reason to make it more complex, that it needs to be.
From sqlite command line shell tutorial there is a section Using sqlite3 in a shell script:
When the sqlite3 program is launched with two arguments, the second argument is passed to the SQLite library for processing, the query results are printed on standard output in list mode, and the program exits.
So you could try sqlite3 ex.db 'PRAGMA foreign_keys = ON; PRAGMA foreign_keys'