I need some ideas to make my code a bit cleaner for a pretty simple application with a simple database. I have the following idea but it’s not working quite well. This is what I’m doing:
I have many queries on a page (takes up a lot of space and source code looks messy. I’d like to have an index of them in another PHP file that I could call via an include.
Except I ran into a problem. I have a query that looks like this on the external php page.
Queries.php:
$RegisterQuery = sprintf("INSERT INTO `testdb`.`users` (
`user_id`,
`username`,
`password`,
`First Name`,
`Last Name`,
`email`)
VALUES (
NULL,
'%s',
'%s',
'%s',
'%s',
'%s'
);",
mysql_real_escape_string($username),
mysql_real_escape_string($password),
mysql_real_escape_string($first_name),
mysql_real_escape_string($last_name),
mysql_real_escape_string($email));
The problem with this is that even when I don’t query $RegisterQuery with mysql_query() it throws a bunch of MySQL warnings about using the mysql_real_escape_string() and about how it can’t connect. I don’t get how it’s doing this when I’m not even querying the database!
Then again, I could easily ignore the warnings…
I’m just not sure I’m doing this properly in which case I mainly want to ask if there’s a better way of doing this or should I just ignore the warnings?
Your feedback is greatly appreciated! Thanks in advance.
I’d suggest using parameterized queries (via for example mysqli or PDO).
You don’t have to escape the strings if they are parameters to the query. This both makes the code clearer and also makes it easier to write secure code as it is a lot less likely you will leave an SQL injection vulnerability if you consistently use parameterized queries.