single quote error!

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
cap2cap10
Forum Contributor
Posts: 158
Joined: Mon Apr 14, 2008 11:06 pm

single quote error!

Post by cap2cap10 »

Greetings again, PHP Technorati! Ok, this is a common noob problem. I am trying to add responses to a database, but my script causes a mysql error when someone tries to upload data with an apostrophe. Mysql reads it as an extra quote that ends the query! who do I allow single quotes/apostrophes to be added to the database. Here is the code:

Code: Select all

for ($i = 1; $i <= 15; $i++) {
    $response = filter_input(INPUT_POST, 'resp_' . $i, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);

    if (!empty($response)) {
        mysql_query("UPDATE prelim_db SET resp_$i = '$response' WHERE candidateID = '$candidateID'") or die('Query failed: ' . mysql_error());
    }
}

I searched it on the web and there is some mention of mysql real escape string! Please enlighten me as to how to solve this problem! :banghead:

Thanks in advance,

Batoe
oscardog
Forum Contributor
Posts: 245
Joined: Thu Oct 23, 2008 4:43 pm

Re: single quote error!

Post by oscardog »

Code: Select all

$response = mysql_real_escape_string($_POST['resp_' . $i);
Can't say I've ever used input filters so I have no idea if it's safe to use both.
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: single quote error!

Post by social_experiment »

Code: Select all

<?php
for ($i = 1; $i <= 15; $i++) {
    $word = 'resp_';
    $value = $word.$i;
    $response = filter_input(INPUT_POST, $value, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);

    if (!empty($response)) {
        mysql_query("UPDATE prelim_db SET $value = '" . mysql_real_escape_string($response) . "' 
WHERE candidateID = '". mysql_real_escape_string($candidateID) . "' ") or die('Query failed: ' . mysql_error());
    }
}
?>
What happens if you use the code above?
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
User avatar
cap2cap10
Forum Contributor
Posts: 158
Joined: Mon Apr 14, 2008 11:06 pm

Re: single quote error!

Post by cap2cap10 »

Excellent! Mysql real escape string did do the trick! Thanks again, guys!

Batoe
Post Reply