简体   繁体   中英

What's the correct syntax for returning a single value using PDO and mySQL?

I'm trying to switch my sql to PDO but I'm having trouble getting even this simple query to return a value. Surely it can't be this difficult. I've done the same query the old fashioned way and it works perfectly as expected. The PDO version returns nothing. What's the trick here?

This first version returns the value I expect.

  $customfieldid = 676;
  $entityid = 9784549;
  $entitytype = 'familyoverview';

  $sql = "select value
                  from customfieldvalues
                 where customfieldid = ".$customfieldid."
                   and entityid = ".$entityid."
                   and entitytype = '".$entitytype."'";

  $result = mysql_query($sql);

  if($row = mysql_fetch_array($result)) {
    $mysqlvalue = $row["value"];
    echo "<br>mysql value: ".$mysqlvalue;
  }

This PDO version returns nothing.

  $sql = "select value
                  from customfieldvalues
                 where customfieldid = :customfieldid
                   and entityid = :entityid
                   and entitytype = :entitytype";

  $stmt = $pdo->prepare($sql);
  //$stmt->bindValue(':customfieldid', $customfieldid, PDO::PARAM_INT);
  //$stmt->bindValue(':entityid', $entityid, PDO::PARAM_INT);
  //$stmt->bindValue(':entitytype', $entitytype, PDO::PARAM_STR);

  $stmt->bindValue(':customfieldid', 676, PDO::PARAM_INT);
  $stmt->bindValue(':entityid', 9784549, PDO::PARAM_INT);
  $stmt->bindValue(':entitytype', 'familyoverview', PDO::PARAM_STR);

  $pdovalue = $stmt->fetchColumn();
  echo "<br>pdo value: ".$pdovalue;

I've confirmed that I have a pdo database connection. I've tried using the third parameter and omitting the third parameter in the bindValue calls. I've also tried hardcoding the values in the bindValue calls vs passing them in but none of that makes any difference.

Your PDO code is missing a call to $stmt->execute() , so the query is never sent to the MySQL server and executed. Without executing the query, there can't be any results.

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