简体   繁体   中英

Special characters in PDO select statement

Im asking this because I have been beating my head on a wall for a something that more than likely has a simple solution. My problem is that I am trying to select a record that contains a unique id similar to "ss&246i". If the statement doesnt contain an & symbol it returns just fine but if it has one I get no return. Here is my code to compliment my problem:

<?php
@session_start();

if (isset($_POST['code'])) {
    $id = $_POST['code'];
    $db = new PDO('mysql:host=localhost;dbname=example', 'example', '******');
    $db->exec("SET CHARACTER SET utf8");

    $sql = "SELECT * FROM tbl_human_readable WHERE unique_id = :id  LIMIT 1";
    $stmt = $db->prepare($sql);
    $stmt->bindValue(":id", $id);
    try {
        $stmt->execute();
    } catch (PDOException $e) {
        echo $e->getCode() . " - " . $e->getMessage();
    }

    $return = $stmt->fetchAll(PDO::FETCH_ASSOC);
    var_dump($return);
    if ($return) {
        $_SESSION['code'] = $id;
        echo "success"; 
    } else {
        echo "failed";
    }
} else {
    echo "failed";
}

As always any help on this is very much appreciated

When solving problems, programmer have to employ knowledge and experience .

Knowledge will tell him that no special character could affect a properly formatted PDO query.
So, it's time to try some experience. Means one have not just staring at the code, but run it. On the purpose of verifying assumptions.

You're assuming that $_POST['code'] contains literal ss&246i value. But you cannot know if it's true or not - you never verified it. So, you have to place a verification code in your script to be sure.

You're assuming that database contains literal ss&246i value. But you cannot know if it's true or not - you never verified it. So, you have to run some code to verify the assumption - try to select a hardcoded literal value instead of posted one.

This way, one by one, verify all your assumptions and find which ones are false. So, you'll be able to either solve the problem on your own or ask a meaningful question on Stack Overflow.

the above process is called debugging and being essential part of programmer's job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM