从数据库列的id返回该列的值

dojqjjoe  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(389)

我试图从数据库列的id返回该列的值。我想在 <span> id为“#姓名#页面”
我在邮寄身份证” $(this).attr("id") "
我有我的ajax电话

$(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);            
    }
  });

然后我在fetch\u 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;

但不可能在我的网页上找回价值

iih3973s

iih3973s1#

您没有获取结果,因此它将是空的,jquery还需要json,因此您需要对响应进行json编码。
在使用pdo时,还应该使用准备好的查询。

<?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);

对于jquery,请尝试以下操作:

$(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);            
      }
   });
});

相关问题