nTuply
nTuply

Reputation: 1364

Double quotes in DB breaking HTML Output

I've tried everything, and I still can't figure it out. addslahes(), str_replace(), htmlentities(), I just can't understand why double quotes are not displaying on my website.

$sql = $con->prepare("SELECT * FROM `user_settings` WHERE `user_session` = '$user_session'");
$sql -> execute();

$result = $sql->fetchAll(PDO::FETCH_ASSOC);

foreach ($result as $row) {
    $advertising_1 = $row['advertising_1'];
    $advertising_2 = $row['advertising_2'];
    $website_name = $row['website_name'];
    $website_url = $row['website_url'];
    $statistics = $row['statistics'];
}
echo '<input type="text" name="website_name" placeholder="Your Website URL" value="'. $website_name. '" />' ?>

Can someone please explain where I'm going wrong here? Problem arises with Double quotes in my string. Single quotes was fixed with mysql_escape but it appears to be deprecated.

Upvotes: 4

Views: 2868

Answers (2)

Hygison Brandao
Hygison Brandao

Reputation: 718

You need to use the prepare without variables on the statement and later you add them on the execute() as an array, like this:

$sql ="SELECT * FROM `user_settings` WHERE `user_session` = ?";
$stmt = $con->prepare($sql);
$stmt->execute([$user_session]);

Upvotes: 0

chris85
chris85

Reputation: 23892

You need to escape the data you are outputting to the browser use htmlspecialchars and use the quotes constant (ENT_QUOTES) so all quotes are converted to entities. Note this also is how XSS injections are prevented/performed. Elements/attributes are closed when they aren't suppose to be and then malicious code is written.

echo htmlspecialchars('Encode all of these "test" test \'test \'', ENT_QUOTES);

Output:

Encode all of these &quot;test&quot; test &#039;test &#039;

and in a browser:

Encode all of these "test" test 'test '

Also from the code you displayed you are misusing prepared statements. Values need to be bound, not concatenated to your query. This way the PDO driver will handle the quoting/escaping. This could result in similar issues for you in the future, if you continue to use it as you have it. Also opens you to SQL injections.

For more information on prepared statements see: http://php.net/manual/en/pdo.prepared-statements.php

Upvotes: 4

Related Questions