MySQL PDO Tutorial Lesson 6 – Prepared statements with placeholders




Enrol on the course at https://www.webinaction.co.uk/p/mysql-pdo-tutorial to download the Working Files. How to use placeholder question marks in prepared …

Original source


11 responses to “MySQL PDO Tutorial Lesson 6 – Prepared statements with placeholders”

  1. <?php
    include 'connect.php';

    $stmt = $db->prepare("SELECT * FROM users WHERE factory = ?");
    $stmt->bindValue(6,'Royal Fashion');
    $stmt->execute();
    var_dump($stmt);
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    echo "<pre>";
    var_dump($row);
    }
    and I m getting
    (PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:xampphtdocspdotutorialprepare.php on line 6
    object(PDOStatement)#2 (1) { ["queryString"]=> string(37) "SELECT * FROM users WHERE factory = ?" })

    users
    [0]=>id [1]=> username [2]=> password [3]=>firstname [4]=>lastname [5]=>contact [6]=>factory [7]=>level [8]=>job

  2. Richard, could you tell me if this statement should work as I am not sure whether it is the statement or the fact I am using it in the wrong place within the code as I am using password_verify()

    if($pdo){
    $stmt = $pdo->prepare("select * from users where username = :username && password = :password");
    $stmt->bindParam(":username", $username);
    $stmt->bindParam(":password", $unhashed);
    echo '<pre>';
    if($stmt->execute()){
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    print_r($rows);
    }

    }
    echo '</pre>';

    If I run the statement with just username = :username I get an array returned but the password is causing an issue.

    Thanks

  3. Richard, for some reason the wildcard is not working for me, could you advise please. My code is below. My dbase columns are first last and postcode

    $stmt = $db->prepare("SELECT * FROM names WHERE LIKE ?");
    $stmt->bindValue(1, '%d%');
    $stmt->execute();

    while($row = $stmt->fetch(PDO::FETCH_ASSOC)){

    $first = htmlentities($row['first']);
    $last = htmlentities($row['last']);
    $pcode = htmlentities($row['postcode']);

    echo $first . ' ' . $last . ' ' . $pcode . $space;

    }

    Thanks

Leave a Reply