Skip to content
Advertisement

PDO query not returning correctly [closed]

I cannot get the specific user query to return in the if section (else works fine):

if ( isset( $_POST[ 'name' ] ) ) {
    $person = $_POST[ 'name' ];
    $stmt = $pdo->prepare("SELECT AVG(ans_1) AS Average FROM responses WHERE email =?");
    $stmt->bind_param("s", $person);
    $stmt->execute();
} else {
    $stmt = $pdo->query("SELECT AVG(ans_1) AS Average FROM responses");
}

$result = $stmt->fetchColumn();
$json = json_encode($result);
echo $json;

The php is called by ajax supplying the variable with POST:

var user = "ratsnitchbrianthegoodtimeruiner";
$.ajax({
          url: "test.php",
          type: "POST",
          data: {name: user},
          dataType: "json",
          success: function (data) {
              alert(data);
}
});

I know my ajax script POST variable is working because when I change the dataType to html, and modify the php to just throw in two echo commands like so:

if ( isset( $_POST[ 'name' ] ) ) {
    $person = $_POST[ 'name' ];
    echo $person;
} else {
    echo ("No one set");
}

The alert(data) prompt in success works fine.

So it must be something amiss with my PDO statements in the if? The else returns the data just fine.

Thanks for any help!

###################################

Note to whoever merged to this question: Receive JSON POST with PHP It does not relate.

I am able to get the POST data (username) just fine. (they were not in that question).

I am getting response in json just fine on the else statement (again an issue in that question that isn’t a problem here).

90 minutes later..

Advertisement

Answer

You’re using MySQLi syntax to bind the parameter, rather than PDO syntax. It should be:

    $stmt = $pdo->prepare("SELECT AVG(ans_1) AS Average FROM responses WHERE email = :email");
    $stmt->bindParam(":email", $person);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement