PHP用於解析JSON並添加到數據庫mysql

[英]PHP for parsing JSON and adding to database mysql


I am making a web app (android) with phonegap and jquery mobile.

我正在制作一個帶有phonegap和jquery mobile的網絡應用程序(android)。

I am trying to send three fields from an html form as json, to a php page which will decode the json string/object (im new to json, ajax, jquery) and add the three fields as a mysql query to a database on my localhost.

我試圖將一個html表單中的三個字段作為json發送到一個php頁面,該頁面將解碼json字符串/對象(即時為json,ajax,jquery)並將三個字段作為mysql查詢添加到我的數據庫中本地主機。

My html page looks like this:

我的html頁面如下所示:

<script type="text/javascript">
$(document).ready(function(){  
$('#btn').bind('click', addvalues);
});
  function addvalues(){
  $.ajax({  
  url: "connection.php",
  type: "POST",  
  data: "id=" + $("#id").val()+"&name=" + $("#name").val() + "&Address=" + $("#Address").val(),
   datatype:"json",
   success: function(status)
  {  
    if(status.success == false) 
    {  
        //alert a failure message
    } 
    else { 
          //alert a success message
        }  
   }  
 });  
} 
</script> 
</head> 
<body> 

<div data-role="header">
<h1>My header text</h1>
</div><!-- /header -->
<div data-role="content">
<form id="target" method="post">
<label for="id">
<input type="text" id="id" placeholder="ID">
</label>
<label for="name">
<input type="text" id="name" placeholder="Name">
</label>
<label for="Address">
<input type="text" id="Address" placeholder="Address">
</label>
<input type="submit" id "btn" value="Add record" data-icon="star" data-theme="e">
</form>
</div>
</body> 

The Question is:

How exactly do i extract the three fields (ID, name, Address) from the string that i have sent to my php file (connection.php)? connection.php is hosted by my local server.

我究竟如何從我發送到我的php文件(connection.php)的字符串中提取三個字段(ID,名稱,地址)? connection.php由我的本地服務器托管。

I am familiar with making connections to database, as also with adding queries to mysql. I only need help with extracting the three fields, as i am new to ajax and jquery and json.

我熟悉與數據庫的連接,以及向mysql添加查詢。我只需要提取三個字段的幫助,因為我是ajax和jquery和json的新手。

As of now, this is ALL i have done in connection.php:

截至目前,這是我在connection.php中做的所有事情:

<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "jqueryex";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);

//I do not know how to use the json_decode function here


//And this is how, i suppose, we will add the values to my table 'sample'
$sql = "INSERT INTO sample (id, name, Address) ";
$sql .= "VALUES ($id, '$name', '$Address')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Comment added";
}
mysql_close($con);
?>

Please add the relevant code in this file and help me out. I will be highly obliged. :)

請在此文件中添加相關代碼並幫助我。我將非常感激。 :)

4 个解决方案

#1


3  

what you want to do this this

你想做什么呢

           $(document).ready(function () {
        $('#btn').on('click', function () {
            $.ajax({
                url: "connection.php",
                type: "POST",
                data: {
                    id: $('#id').val(),
                    name: $('#name').val(),
                    Address: $('#Address').val()
                },
                datatype: "json",
                success: function (status) {
                    if (status.success == false) {
                        //alert a failure message
                    } else {
                        //alert a success message
                    }
                }
            });
        });
    });

then in your php do this

然后在你的PHP做到這一點

   //set variables from json data
    $data = json_decode($_POST); // Or extract(json_decode($_POST) then use $id without having to set it below.
    $id = $data['id'];
    $name = $data['name'];
    $Address = $data['Address'];

    //And this is how, i suppose, we will add the values to my table 'sample'
    $sql = "INSERT INTO sample (id, name, Address) ";
    $sql .= "VALUES ($id, '$name', '$Address')";
    if (!mysql_query($sql, $con)) {
        die('Error: ' . mysql_error());
    } else {
        echo "Comment added";
    }
    mysql_close($con);

be sure you sanitize those inputs before you insert them though.

確保在插入之前清理這些輸入。

#2


1  

use:

使用:

$id = json_decode($_POST['id']);
$name = json_decode($_POST['name']);
$Address = json_decode($_POST['Address']);

$sql .= "VALUES ($id, '$name', '$Address')";

in place of :

取代:

$sql .= "VALUES ($id, '$name', '$Address')";

#3


0  

use $id_json_encoded = json_encode($_POST['id']); to encode the posts of the form then use jquery script like this

使用$ id_json_encoded = json_encode($ _ POST ['id']);要對表單的帖子進行編碼,然后使用這樣的jquery腳本

<script type="text/javascript">

$(document).ready(function() {

$(document).ready(function(){

        $("#audit").click(function(){
            $.post("/audit_report/"+$('#branch').val()+"/"+$('#ttype').val()+"/"+$('#from').val()+"/"+$('#to').val(),

                    {
                        targetDiv:"divswitcher"
                    }
                ,
                    function(data){

                     $("#imagediv").html('<img src="/public/images/spinner_white.gif"> loading...');  
                //alert(data);
                $("#bodydata").html(data);
                 $("#imagediv").html('');  
                    //  $("#divswitcher").html(data);
        });                 
        });     
        });     

#4


0  

this is the complete code that encodes form data and send it to the server using ajax


<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <script type="text/javascript" charset="utf-8" src="jquery.js"></script>
<script type="text/javascript" language="javascript" src="jquery-ui-1.8.16.custom.min.js"></script> 





    <script type="text/javascript">
$(document).ready(function()
  { 


            $("#btn").click(function(){

            var encoded = json_encode("/audit_report/"+$('#id').val()+"/"+$('#name').val()+"/"+$('#Address').val());
                $.post(encoded,

                        {
                            targetDiv:"divswitcher"
                        }
                    ,
                        function(data){

                         $("#imagediv").html('<img src="spinner_white.gif"> loading...');  
                    //alert(data);
                    $("#bodydata").html(data);
                     $("#imagediv").html('');  
                        //  $("#divswitcher").html(data);
            });                 
            });     
            });     
</script>


</head>
<body>

    <div data-role="header">
<h1>My header text</h1>
</div><!-- /header -->
<div data-role="content">
<form id="target" method="post">
<label for="id">
<input type="text" id="id" name="id" >
</label>
<label for="name">
<input type="text" id="name" name="name" >
</label>
<label for="Address">
<input type="text" id="Address" name="Address" >
</label>

<input type="button" id="btn" name="btn" value="Add record" />
</form>
</div>

</body>
</html>


<div id="bodydata" class="class">

</div>

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/07/06/6f2d3d82102a58102bf0e3d604d5b0ac.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com