php - return the value of a database column from its ID

945

I try to return the value of a database column from its ID. I want to display it in a<span> with that ID "#name_page"

I'm sending the ID through POST "$(this).attr("id")"

I have my AJAX call

$(document).on('click', '.update_btn', function(e){
   e.preventDefault();
      $.ajax({
      url:"fetch_single.php",
      type:"POST",
      data:{
        user_id: $(this).attr("id"),
      },
      success:function(data) {  
        $('#name_page').val(data.name_page);
        $('#user_id').val(user_id);            
    }
  });

Then I receive it in fetch_single.php

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT name_page FROM table WHERE id = '".$_POST["user_id"]."' 
        LIMIT 1"); 
    $stmt->execute();
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;

But impossible to get the value back in my webpage

86

Answer

Solution:

Your not fetching the result, so it will be empty, jquery is also expecting json so you need to json_encode your response.

Also as your using PDO you should be using prepared queries.

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";

$json = [];

// is POST
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // check user_id
    if (!isset($_POST["user_id"]) || !is_numeric($_POST["user_id"])) {
        exit(json_encode(['error' => 'Invalid user id']));
    }

    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $conn->prepare("SELECT name_page FROM table WHERE id = ? LIMIT 1"); 
        $stmt->execute([$_POST["user_id"]]);

        $json = ['name_page' => $stmt->fetchColumn()];
    }
    catch(PDOException $e) {
        $json = ['error' => $e->getMessage()];
    }
    $conn = null;

} else {
    $json = ['error' => 'Sorry expecting POST'];
}

echo json_encode($json);

For your jQuery try this:

$(document).on('click', '.update_btn', function(e){
    e.preventDefault();

    var user_id = $(this).attr("id");

    $.ajax({
      url:"fetch_single.php",
      type:"POST",
      dataType: "json",
      data:{
        user_id: user_id,
      },
      success: function(data) {
        $('#name_page').val(data.name_page);
        $('#user_id').val(user_id);            
      }
   });
});

People are also looking for solutions to the problem: php - Mysqli stopped working because of fetch issue

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.