Paranoid Android
Paranoid Android

Reputation: 5037

Escape hyphen in PHP /mySQL query

The following line throws an error:

$query = "INSERT INTO mail_senders(mailAddress) VALUES ('$_POST[sender-email]')";

and the problem is the hyphen "-"

I might easily change "-" with "_" but I would like to know if it possible to escape that character for future reference.

Thanks in advance

Upvotes: 2

Views: 5859

Answers (3)

ASpencer
ASpencer

Reputation: 1363

First of all, as your code stands, you're vulnerable to SQL injection - you should really look at parameterized queries.

Without being sure of the kind of database you're using, I'll write this using Mysqli:

$dbUser = 'username';
$dbPass = 'password';
$dbHost = 'localhost';
$dbName = 'databasename';

$dbConnection = new mysqli($dbHost,$dbUser,$dbPass,$dbHost); 

$query = "INSERT INTO mail_senders (mailAddress) VALUES (?)";
if ($statement = $dbConnection->prepare($query)) {
    $statement->bind_param('s',$_POST['sender-email']);
    $statement->execute();

    //If this was a select statement, do stuff with result set here...
    ...
    ...
    ...

    //As this is an insert, you'll probably want to know if you've successfully inserted a row so...
    if ($statement->affected_rows > 0) {
        //Snip - update successful.
    }
  
    //And then close the connection
    $statement->close();
}
    

For more info on prepared statements with mysqli, look at the mysqli prepare documentation.

Upvotes: 0

Otar
Otar

Reputation: 2591

Should be $_POST['sender-email']

$query = "INSERT INTO mail_senders(mailAddress) VALUES ('{$_POST['sender-email']}')";

Upvotes: 0

halfdan
halfdan

Reputation: 34204

To prevent SQL injection you should escape your input. Then use sprintf for readability and use quotes for the index of the array. If you don't use quotes PHP sees sender-email as undefined constant and assumes that you actually mean the string "sender-email". If at some point you define sender-email your code will probably break.

$query = sprintf("INSERT INTO mail_senders(mailAddress) VALUES ('%s')", mysql_real_escape_string($_POST["sender-email"]));

Upvotes: 5

Related Questions