We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to create array-json variable with Phalcon?

In my previous projects using the jquery autocomplete. This function consisted of two parts

Number one.jquery function

<script>
            $(function() {
            $(".auto").autocomplete({
            source: "search_producto.php",
            minLength: 1,
            select: function(event, data) {
                    $("#codigo").val(data.item.ide);
                    $("#iva").val(data.item.iva);
                    $("#descuento").val(data.item.descue);
                    $("#disponible").val(data.item.dispo);
                    $("#precio").val(data.item.precio);
                    $("#unidad").val(data.item.unidad);
                    $("#producto").val(data.item.value);
                    $(".auto").val(data.item.value);
                    $("#cant").focus();
                    },
                });
        });
</script>

number two The file search_producto.php

<?php
if (isset($_GET['term'])){
$return_arr = array();
try {
 $db_username = "SPOLS";
$db_password = "SPOLS";
$db = "oci:dbname=JEIEL/XE";
$conn = new PDO($db,$db_username,$db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT P.PROD_CODIGO, P.PROD_NOMBRE, P.PROD_CODIG1, P.PROD_UNIDAD ,PROD_CODIG2,PROD_IVA FROM MAE_PROD P  WHERE P.PROD_ESTADO='1' AND P.PROD_TIPOXX='PRO' AND P.PROD_NOMBRE LIKE :term");
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
 while($row = $stmt->fetch()) {
$return_arr[] = array('value' => $row['PROD_NOMBRE'], 'nombreproducto' => $row['PROD_NOMBRE'], 'ide' => $row['PROD_CODIGO'], 'unidad' => $row['PROD_UNIDAD'], 'precio' => '2.25', 'descuento' => '0.00', 'iva' =>$row['PROD_IVA'], 'serial' => $row['PROD_CODIG1'], 'barra' => $row['PROD_CODIG2'],'dispo'=>'0.00');
}
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

header('Content-type: application/json');
echo json_encode($return_arr);
}
?>

The second file is a class that stores data me my table in an array that sent as json. How do I create the array to store data from my table?

You must log in first to vote

edited Jun '16

C. 42

edited Jun '16

@Lajos LOOOOOOOOOOOOOL :D

@jeiel Just send data as ajax to your controller and return the results as json? Something like:

        $this->response->setContentType('application/json', 'UTF-8');
        return $this->response->setJsonContent($this->_data)->send();

In latest versions of Phalcon that setContentType is not need when u use return with setJsonContent ... u can check that here: https://github.com/phalcon/cphalcon/blob/2.1.x/phalcon/http/response.zep#L528 :P soo...

@Lajos LOOOOOOOOOOOOOL :D

@jeiel Just send data as ajax to your controller and return the results as json? Something like:

       $this->response->setContentType('application/json', 'UTF-8');
       return $this->response->setJsonContent($this->_data)->send();


81.1k
edited Jul '16

Hi, sorry I was doing other pending changes this is the product for some reason does not work I will review the jquery. If something look bad me know please

In my controller

public function buscarProductoAction(){
            $sql = "
            select ART_CODIGO, ART_NOMBRE, nvl(ART_costo,0)  as costo,ART_UNIDADC as UNIDAD, NVL(ART_IVA,0) AS IVA from SPM_ARTICULO WHERE ART_ESTADO<>'A'  AND ART_NOMBRE LIKE   "."'%".$_GET['term']."%'";
        $robots = $this->db->fetchOne($sql);
        foreach ($robots as $robot) {
            $return_arr[]=array('id'=>$robot['ART_CODIGO'],'ART_NOMBRE'=>$robot['ART_NOMBRE'],'COSTO'=>$robot['COSTO'],
                                'UNIDAD'=>$robot['UNIDAD'],'IVA'=>$robot['IVA']);
        }
        $this->response->setContentType('application/json', 'UTF-8');
        return $this->response->setJsonContent($return_arr)->send();

    }

In my view

<script>
            $(function() {
            $(".auto").autocomplete({
            source: "buscarProducto",
            minLength: 1,
            select: function(event, data) {
                    $("#codigo").val(data.item.id);
                    $("#iva").val(data.item.IVA);
                    $("#precio").val(data.item.COSTO);
                    $("#unidad").val(data.item.UNIDAD);
                    $("#producto").val(data.item.ART_NOMBRE);
                    $(".auto").val(data.item.ART_NOMBRE);
                    $("#cant").focus();
                    },
                });
        });
</script>

In the jquery i have this problem

jquery.js:9203 GET https://localhost/tesis/spt_encabezado/buscarProducto?term=m 500 (Internal Server Error)

It is
try {

                    // Do send the request (this may raise an exception)
                    xhr.send( options.hasContent && options.data || null );

I feel I have error in the Loop

Please check your error_log to see what is causing the 500 error.

Also few things to note:

  • Do not use directly $_GET, but use Phalcon's request class. $this->request->getQuery('your_param'). More info here.
  • You are using fetchOne which returns only 1 result, perhaps you need multiple results? Read about other methods and fetchAll here


81.1k

In the log file

[Sat Jul 02 01:39:41.850838 2016] [:error] [pid 25446] [client 127.0.0.1:28872] PHP Warning:  Illegal string offset 'ART_CODIGO' in       /var/www/html/tesis/app/controllers/SptEncabezadoController.php on line 70, referer: https://localhost/tesis/spt_encabezado/new
[Sat Jul 02 01:39:41.850887 2016] [:error] [pid 25446] [client 127.0.0.1:28872] PHP Stack trace:, referer: https://localhost/tesis/spt_encabezado/new    

Is the foreach if it is well done it?

Please read the documentation in fetchAll link i gave you. After that var_dump your $robots and see exactly what type the result is. It is most likely object and you are trying to access it like array $robot['ART_CODIGO']



81.1k
edited Jul '16

I made the following changes


     public function buscarProductoAction() {

        if (isset($_GET['term'])) {
               $robots = SpmArticulo::find("ART_NOMBRE LIKE  %'".$_GET['term']."%'");
            foreach ($robots as $robot) {
                $return_arr[] = array('id' => $robot->ART_CODIGO,
                    'ART_NOMBRE' => $robot->ART_NOMBRE,
                    'COSTO' => $robot->ART_COSTO,
                    'UNIDAD' => $robot->ART_UNIDADV, 'IVA' => $robot->ART_IVA);
                $this->response->setContentType('application/json', 'UTF-8');
                return $this->response->setJsonContent($return_arr)->send();
            }
            //var_dump($return_arr);
        }
    }

In the var_dump


    array (size=2)
    0 => 
    array (size=5)
      'id' => string 'ARTIC0000000002' (length=15)
      'ART_NOMBRE' => string 'MEMORIA USB STANDAR 2' (length=21)
      'COSTO' => string '0' (length=1)
      'UNIDAD' => string 'U' (length=1)
      'IVA' => string '0' (length=1)
    1 => 
      array (size=5)
      'id' => string 'ARTIC0000000001' (length=15)
      'ART_NOMBRE' => string 'MAQUINA DE VOTACION' (length=19)
      'COSTO' => string '0' (length=1)
      'UNIDAD' => string 'U' (length=1)
      'IVA' => string '0' (length=1)

IT'Ś OK

But when returning only returns a row in the array, the array not all this I checked with the tools of google chrome



93.7k
Accepted
answer

What does not work exactly? Your final array looks perfect for json output?

Also I would recommend reading this page: https://docs.phalcon.io/en/latest/reference/models.html Your query is not safe and you could get hacked if you search by user input.

// This is not safe. You could get SQL injection
$robots = SpmArticulo::find("ART_NOMBRE LIKE  %'".$_GET['term']."%'");

// This is safe
$robots = SpmArticulo::find(array(
  'conditions' => 'ART_NOMBRE LIKE :artNumber:',
  'bind' => array(
     'artNumber' => '%'. $this->request->getQuery('term') .'%'
  )
));


81.1k

Thanks has been very helpful.