Post php array Insert mysql

Asked

Viewed 150 times

0

I have a Javascript form that sends a array, however I am not able to recover the columns and their values of the array to insert into a Mysql database with PHP.

Example of array

{"id_deb":"","codbar":"123","id_cat":"20","id_emp":"89","date_at":"2019- 
04-25","valor":"222.22","status":1}

PHP code

<?php
include ('../../../../../../server/lib/Connection.class.php');


        //print_R($_POST);
        $sql = "INSERT INTO `debitos` (codbar,categoria_id,empresa_id) VALUES('" . $_POST["codbar"] . "', '" . $_POST["id_cat"] . "','" . $_POST["id_emp"] . "')";
        $result = @mysql_query($sql);
if ($result){
    echo json_encode(array('success'=>true));
} else {
    echo json_encode(array('msg'=>'Erro ao inserir dados.'));
}




?>
  • Hello @Aiolos, welcome to Sopt! Add your code php so that the staff can help, without it becomes difficult to assist in the solution.

  • include ('../../.../../../server/lib/Connection.class.php'); //print_R($_POST); $sql = "INSERT INTO debitos (codbar,categoria_id,empresa_id) VALUES('" . $_POST["codbar"] . " ', '" . $_POST["id_cat"] . " ','" . $_POST["id_emp"] . " ')"; $result = @mysql_query($sql); if ($result){ echo json_encode(array('Success'=>true); } Else { echo json_encode(array('msg'=>'Error inserting data. '); }

  • Add the code to the question for easy reading

  • Missing javascript code sending array

  • Must-read: Why should we not use mysql type functions_*? And never use the @ in function calls. If you do not know what is happening, it will only harm you; if you know what is happening you will avoid.

  • How does it get in php?

Show 1 more comment

1 answer

0


before anything else I suggest you take note of this information: Why should we not use mysql type functions_*?

What you are sending is a JSON not a Array. The $_POST is an associative array of variables passed to the current script via HTTP POST method when used application/x-www-form-urlencoded or multipart/form-data as HTTP header value Content-Type in the request.

For you to recover the data from JSON sent you can make use of the code below:

<?php
require '../../../../../../server/lib/Connection.class.php';

$dados = json_decode(file_get_contents('php://input'));


$sql = "INSERT INTO `debitos` (codbar,categoria_id,empresa_id) VALUES ('" . $dados->codbar . "', '" . $dados->id_cat . "','" . $dados->id_emp . "')";
$result = @mysql_query($sql);

if ($result){
    echo json_encode(array('success'=>true));
} else {
    echo json_encode(array('msg'=>'Erro ao inserir dados.'));
}

Remember that the above code is not recommended and it is subject to attacks from SQL Injection.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.