简体   繁体   English

将数据库查询结果格式化为JSON数组并读入表单

[英]Format Database Query Results into a JSON Array and Read into Form

I currently have this code which reads the first field in a database record which is specified by the user ('myid' being a text field which accepts a number) and prints it in one of the fields of a front end form. 我目前有这个代码读取数据库记录中的第一个字段,该字段由用户指定('myid'是接受数字的文本字段)并将其打印在前端表单的一个字段中。

How do I make a JSON array of all of the fields in the database and then print them to the relevant form field? 如何创建数据库中所有字段的JSON数组,然后将它们打印到相关的表单字段? Thanks 谢谢

Back-End Code 后端代码

 $id = $_POST['id'];

 $query = "SELECT * FROM Customers WHERE ID = '" . mysql_real_escape_string($id) . '"';
 $result= mysql_query($query);

 if (mysql_num_rows($result) > 0) { 
      while($row = mysql_fetch_row($result)) {

         echo $row[1];
               }
         }

else { 
// no 
// print status message 
echo "No rows found!"; 
     }

Front-End Code 前端代码


 jQuery(document).ready(function(){ 
 jQuery("input.myid").keyup(function(e){ 
 e.preventDefault(); 
 ajax_search(); 
          }); 
     });

 function ajax_search(){
 var search_val=jQuery("input.myid").val(); 
 jQuery.post("find.php", {id : search_val}, function(data){

 jQuery("input.fname").val(data);  

        }   
)}

You can use function json_encode() to convert an array into json format. 您可以使用函数json_encode()将数组转换为json格式。 And convert to array from json using function json_decode(). 并使用函数json_decode()从json转换为数组。

you have to just pass one parameter in function that is the array you want to encode or decode. 你必须在函数中传递一个参数,即你要编码或解码的数组。

header("HTTP/1.0 200 OK");
header('Content-type: text/json; charset=utf-8');
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Pragma: no-cache");
if (mysql_num_rows($result) > 0) 
{
    while($row = mysql_fetch_row($result)) {
        echo json_encode( $row );
    }
}
else 
{ 
    // no 
    // print status message 
    echo json_encode( "No rows found!" );
}
die();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM