Link to home
Create AccountLog in
Avatar of Steynsk
SteynskFlag for Netherlands

asked on

Store a Sql statement in a mysql database

Hi Experts,

I would like to store a SQL statement in my database with a insert from PHP. What would be a syntax that works?

Thanks,

Steynsk
Avatar of gr8gonzo
gr8gonzo
Flag of United States of America image

mysql_query("INSERT INTO your_database_table (column_a,column_b) VALUES ('value for column a','value for column b')");
Avatar of Steynsk

ASKER

Hi gr8gonzo,

Thanks for the quick response. But I need to store a complete sql statement/query as a value in to database field.

something like:

$sql = "Select *from my_other_table";
mysql_query("INSERT INTO your_database_table (statement) VALUES ('".$sql."')");

But this does not work...
The statement looks OK, but what do you mean by 'does not work'. Any errors etc?

FYI, you shouldn't be using mysql_query any more - mysqli or PDO
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of Steynsk

ASKER

the answer I was looking for is more simple I found it my self:


$sql = "Select *from my_other_table";
$sql = addslashes($sql);
mysql_query("INSERT INTO your_database_table (statement) VALUES ('".$sql."')");
FYI, you shouldn't be using mysql_query any more - mysqli or PDO
Addslashes shouldn't change anything unless you've got quotes inside the SQL statement you're trying to store.

Also, I should mention that storing raw SQL commands into databases is almost always a bad idea. You should always assume that at some point, you will write a piece of code that is not secure, and that a malicious person will try to exploit that code and push unwanted/unexpected data into your database.

That said, what would happen if a malicious user updated your SQL statements or created new ones that simply dropped tables or deleted data or something else? For that matter, what could a malicious user do if he/she could run SQL commands against your database?

If you just cannot avoid storing SQL commands, then I would at least consider some additional security options. If all you need is SELECT statements, then store the table name and WHERE clause into different fields, and then reconstruct the full SELECT statement later. You can also store a hash or something that would be like a "signature" that indicated that the command was inserted by a legitimate person. That way, a malicious user would be less likely to be able to forge the signature and you would be able to trust the SQL statements a little more.

However, if you CAN avoid putting SQL commands into your database, trust me, avoid it.
@Chris - that's true, but some people don't have mysqli enabled just yet. I do agree that mysqli is always the best option over mysql if it is enabled.