Search code examples
mysqlquotes

Not working mysql_query in php (quotation marks probs)


$ikona = "layout/achiv/a_icon.png";
//$opis = string of text without quotation marks

$addit = '<img src="'.$ikona.'" onclick="alert(/'On day '.date("Y-m-d H:i:s").' user has '.htmlspecialchars($opis).'/'); ">';

mysql_query("UPDATE `accounts` SET `this_damn_cell`='".$addit."'
WHERE id='".$_POST["id"]."' ") or die(mysql_error()); //error is not showing up

echo $addit; //shows correctly

It seems to work okay, but in sql base nothing is getting added. All fields exists. this_damn_cell type is TEXT For any assistance thanks in advance :)


Solution

  • Your code reads MySQL Injection all along.

    For a quick-fix with mysql_escape_string please change your code to the following:

    $sql = sprintf('UPDATE accounts 
                    SET this_damn_cell = %s
                    WHERE id='%i", mysql_escape_string($addit), mysql_escape_string($_POST['id']);
    
    mysql_query($sql) or die(mysql_error()); //error is not showing up
    

    But do read a bit on prepared statements. Using PDO or MySQLi.

    Taken from PHP site this is a simple example of using MySQL with binding (which does prevent MySQL injection and the sort of errors you're facing).

    $stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
    $stmt->bind_param('sssd', $code, $language, $official, $percent);