This code works.

... $se = $conn->query("SELECT ... ;"); $se ->setFetchMode(PDO::FETCH_ASSOC); $n = 1; while($row = $se->fetch()) { $x=$x.'"'.$n++.'":"'.$row[p1].'","'.$n++.'":"'.$row[p2].'",'; $c1 = $row[c1]; $c2 = $row[c2]; $c3 = $row[c3]; } ... 

Select returns a table in which the columns c1, c2, c3 always have the same values. If I understood correctly, then the variable “under json” is formed in the loop. And in the same cycle, at each iteration, the variables c are assigned the same values. How to carry out such assignment for a cycle?

    2 answers 2

    No Well, that is, it is possible to pervert, but there is no point in this anyway.

    In addition, there should be no manual formation "under json". If the result of the query should be given in the form of json, then you should use the standard tools:

     $stmt = $conn->query("SELECT ... "); $data = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode($data); 
    • It is clear, thank you, I will digest regular means. - Alex
    • can you clarify? If to do by regular means , then I get the actual names of the fields in the table subd as the data keys on the client . It seems like it is not very good to shine them. In my manual shaping, the keys are a sequence of numbers, instead of names; data, where necessary - I can wrap in addslashes. Such keys are easy to process on the client. That is, is there a significant profit in json_encode () and what’s the problem with manual json assembly? Thank. - Alex
    • Although you probably can give aliases to the table fields on the php server. But I wonder if the manual build of json is definitely a bad decision and are there cases in its favor? - Alex
    • one
      There is not the slightest problem in shining field names. There are no reasons for manual json assembly, and there are A LOT of reasons against. No need to bring up to the moment when the client starts to swear at the wrong format. - Ipatiev
    • one
      first, instead of alert, you should start using console.log for a long time and display x immediately. Secondly, x is an object. And thirdly, I repeat - these perversions with the replacement of the names of the fields are not needed by anyone - Ipatyev

    then I get as the data keys on the client the real names of the fields in the table

    You can assign aliases to the displayed fields directly in the SQL query: SELECT col1 AS "psudo1", col2 AS "pseudo2 FROM table"

    • I wrote about this in the comments above ... - Alex