0

i want to retrieve 3 information from the database based on the ID number input. when i type number 5 in an <input id="id"> html markup. get the name, age, email of the associated number and insert it on a dedicate <input> box for each result

how do i get the multiple result from my query and then input the result on my <input> markup

<input id="name">  //insert name from db
<input id="age">  //insert name from db
<input id="email">  //insert name from db

below is my code, where it only fetches the name from the database and input it on an <input id="name"> markup.

My Jquery

var id = $('input#id').val(); //get value of input box
$.post('./ajax/getdata.php', {id: id}, function(data) //pass this to getdata.php
{
$('input#name').val(data);

}

MY getdata.php

if (isset($_POST['id']) === true && empty($_POST['id']) === false) 
{
require '../connect.php';

$query = "SELECT * FROM `members` WHERE `memberNo` = '" . mysql_real_escape_string(trim($_POST['id'])). "' ";
$result = $db->query($query);

   while ($row = $result->fetch_assoc()) 
   {
   echo $row['firstname'];

   }
}
4

1 回答 1

0

首先,由于你id必须是独一无二的,你不需要做一个while循环。

而且由于您要返回一个 ajax 调用,因此 JSON 可能是最好的数据格式(也是 jQuery 的默认格式)。

所以在你的 getdata.php 中:

if (isset($_POST['id']) === true && empty($_POST['id']) === false) 
{
    require '../connect.php';

    $query = "SELECT * FROM `members` WHERE `memberNo` = '"
            . mysql_real_escape_string(trim($_POST['id'])). "' ";
    $result = $db->query($query);
    $row = $result->fetch_assoc()
    // setting the appropriate content type
    header('Content-Type: application/json');

    echo (json_encode($row));
}

你在success回调中处理这个:

var id = $('input#id').val(); //get value of input box
$.post('./ajax/getdata.php', {"id": id}, function(data)
{
    $('input#name').val(data.firstname);
    $('input#age').val(data.age);
    $('input#email').val(data.email);
}
于 2013-09-26T03:39:58.247 回答