Reputation: 3245
I have a mysql query inside a php file which is selecting a bunch of names from a table and populating a drop down list. That's my first sql statement.
$sql1 = "SELECT DISTINCT AuthorLast FROM Author ORDER BY AuthorLast";
The issue is that one of the names is O'Kiefe.
My second sql statement is as follows, in which I run after pressing the submit button.
The issue is that since the name O'Kiefe contains an apostrophe, it's not running my second sql function the way I want.
$sql2 = "select distinct Book.Title from Book,Author,Wrote where Author.AuthorLast='$_POST[filter2]' and Author.AuthorNum=Wrote.AuthorNum and Wrote.BookCode=Book.BookCode";
Is there a way I can overcome this?...
Hope you can help. Just learning php and mysql . Thanks!
Upvotes: 0
Views: 65
Reputation: 248
You can use PDO (PHP Data Object) to interact with your Data Base, it handles the parametric query in itself and prevent from SQL Injection automatically.
Try this instead:
if($_POST["filter2"]){
$stmt = $conn->prepare("select distinct Book.Title from Book,Author,Wrote where Author.AuthorLast='?' and Author.AuthorNum=Wrote.AuthorNum and Wrote.BookCode=Book.BookCode");
$stmt->execute(array($_POST['filter2']));
}
I recommend PDO (supported as of PHP 5.1)!
Upvotes: 3
Reputation: 4519
You should use
mysql_real_escape_string()
Warning This extension is deprecated as of PHP 5.5.0 , Instead, the MySQLi or PDO_MySQL extension should be used.
$author_last = mysql_real_escape_string($_POST[filter2]);
$sql2 = "select distinct Book.Title from Book,Author,Wrote where Author.AuthorLast='$author_last' and Author.AuthorNum=Wrote.AuthorNum and Wrote.BookCode=Book.BookCode";
Upvotes: 0