PHP - Recibir JSON

 
Vista:
sin imagen de perfil

Recibir JSON

Publicado por tato (7 intervenciones) el 05/06/2014 01:02:45
Hola foro!

Tengo la necesidad de crear un programa en PHP donde reciba como paràmetro datos en formato JSON, según yo ya hice el programa pero no logro que inserte datos en la tabla, el programa lo tengo instalado en un servicio hostting. gracias


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php
 
// Helper method to get a string description for an HTTP status code
// From http://www.gen-x-design.com/archives/create-a-rest-api-with-php/ 
function getStatusCodeMessage($status)
{
    // these could be stored in a .ini file and loaded
    // via parse_ini_file()... however, this will suffice
    // for an example
    $codes = Array(
        100 => 'Continue',
        101 => 'Switching Protocols',
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Found',
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        306 => '(Unused)',
        307 => 'Temporary Redirect',
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Request Entity Too Large',
        414 => 'Request-URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Requested Range Not Satisfiable',
        417 => 'Expectation Failed',
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported'
    );
 
    return (isset($codes[$status])) ? $codes[$status] : '';
}
 
// Helper method to send a HTTP response code/message
function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
    $status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
    header($status_header);
    header('Content-type: ' . $content_type);
    echo $body;
}
 
class RedeemAPI {
    private $db;
    // Constructor - open DB connection
    function __construct() {
        $this->db = new mysqli('localhost', 'futchoco_admin', 'Futcho190867', 'futchoco_futsoft');
       /* verificar la conexión */
       if (mysqli_connect_errno()) {
       	printf("Conexión fallida: %s\n", mysqli_connect_error());
       	exit();
      }
    	$this->db->autocommit(FALSE);
    }
 
    // Destructor - close DB connection
    function __destruct() {
        $this->db->close();
    }
    // Main method to redeem a code
    function redeem() {
    // Check for required parameters
    	$json = file_get_contents('php://input');
    	$obj = json_decode($json,true);
    	print_r($obj);
    	foreach($obj as $item)
    	{
    		$rows[] = "('" . $key . "', '" . $value . "')";
    		$stmt = $this->db->prepare('INSERT INTO prueba(id,nombre)
    				                    VALUES (%d,%d)',$item->value1,$item->value2) or die(mysqli_error($this->db));
    		//$stmt = $this->db->prepare('INSERT INTO detalle_encuentro (id_cliente,id_sucursal,id_torneo,id_jornada,id_juego,id_equipo,enc_locvis,
    		//		                    id_jugador,denc_minuto,denc_gol,denc_roja,denc_amarilla,fehca_mvto,cve_usuario)
    		//		                    VALUES (%d,%d,%d,%d,%d,%d,%s,%d,%d,%d,%d,%d,%s,%s)',$item->cliente,$item->sucursal,$item->id_torneo,$item->id_jornada,$item->id_juego,$item->id_equipo,$item->locvis,$item->id_jugador,$item->minuto,$item->roja,$item->amarilla,fecha,"movil") or die(mysqli_error($this->db));
    		$stmt->execute();
    	}
    }
    sendResponse(400, 'Invalid request');
    return false;
  }
}
 
 
// This is the first thing that gets called when this page is loaded
// Creates a new instance of the RedeemAPI class and calls the redeem method
$api = new RedeemAPI;
$api->redeem();
 
?>
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de jon

Recibir JSON

Publicado por jon (2 intervenciones) el 05/06/2014 01:22:31
Hola tato.
Es curioso, pero te muestro esta aplicación PHP que justamente da solución a tu problema.
https://github.com/alfa30/JRequest

Te permitirá llevar a cabo tus aplicaciones html con AJAX (JSON) sin mayor problema.
Demo
1
2
3
4
5
6
7
8
9
10
11
12
<body>
	La hora es: <span id="clock"></span><br>
	<a id="uploadhora" href="#actuliza">Actualizar</a>
	<script>
		var apturahora = function(){
			$.getJSON("/JRequest/request.php",function(res){
				$("#clock").text(res.clock.date);
			});
		}
		$("#uploadhora").click(apturahora);
	</script>
</body>

y para tu aplicación.
1
2
3
4
5
<?php
 
$out_ajax["clock"] = new DateTime();
 
?>
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Recibir JSON

Publicado por tato (7 intervenciones) el 05/06/2014 15:08:11
Gracias Jon.


El que enviará datos al servidor será una aplicación móvil en formato JSON, en teoria ya se envìa los datos en JSON pero no tengo idea por què el programa en PHP no inserta los datos.


Saludos
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar