I want to load some data from mysql to a div via ajax php. The id field which is auto increment is always equal to zero.
I have tried using get, post etc but none is wor
I assume that customer_id
is a unique key in your database and only one row is returned for each id in your database. So, how to correctly use PDO statements:
$sql = "SELECT * FROM customers WHERE customer_id=:id";
//Prepare your SELECT statement.
$statement = $pdo->prepare($sql);
//The Primary Key of the row that we want to select.
$id = intval($_REQUEST['customer_id']);
//I highly recomment not to use $_REQUEST, use $_GET or even better $_POST
//Bind our value to the paramater :id.
$statement->bindValue(':id', $id);
//Execute our SELECT statement.
$statement->execute();
//Fetch the row.
$row = $statement->fetch(PDO::FETCH_ASSOC);
//If $row is FALSE, then no row was returned.
if($row === false){
echo $id . ' not found!';
} else{
echo 'Found: ' . $row['first_name'];
}
EDIT Also, change your ajax request like this:
$.ajax({
url: 'getCustomerDetails.php',
type: 'POST',
data: {customer_id:uid}
})
Start with debugging your actual result from the database.
if (isset($_REQUEST['customer_id'])) {
$id = intval($_REQUEST['customer_id']);
$query = "SELECT * FROM customers WHERE customer_id=:id";
$stmt = $pdo->prepare( $query );
$stmt->execute(array(':id'=>$id));
$row=$stmt->setFetchMode(PDO::FETCH_ASSOC);
You are NOT checking for errors.
Two suggestions:
1) You are using <?php echo $row['first_name'];?>
. If you inspected the resultset you could see what is wrong with that. Just output the result in the (wrongly named) $row variable with print_r() and the like. I am sure you will see what went wrong.
2) I strong advise AGAINST using $_REQUEST. It is lazy and errorprone. Do you know where the 'customer_id' came from? Session? Cookie? POST? Or Get? If you are passing information via GET => use GET