Array Push Json Database Golang

$sql_query = “
SELECT produkid
,produknm
,tag
,refid
,description
,gambar
,rating FROM produk”;
$result = mysql_query($sql_query) or die (“Error :”.mysql_error());
$categories = array();
$j = 1;
while($category = mysql_fetch_array($result)) {
$tmp = array();
$tmp[‘rank’] = $j + 1;
$tmp[“produkid”] = $row[“produkid”];
$tmp[“produknm”] = $row[“produknm”];
$tmp[“tag”] = $row[“tag”];
$tmp[“rating”] = $row[“rating”];
$tmp[“description”] = $row[“description”];
$tmp[“gambar”] = “http://192.168.131.2:81/eshopper/".$row["gambar”];
// push category to final json array
array_push($response, $tmp);
$j++;
}
// echo json result
echo json_encode($response);

For Example

package main

import (
	"encoding/json"
	"log"
	"os"
)

type Product struct {
	Rank     int
	Prodkid  int
	Produknm string
}

func main() {

	var array []*Product

	for i := 0; i < 10; i++ {
		tmp := &Product{}
		tmp.Prodkid = i
		tmp.Produknm = "162csfr82fr"
		tmp.Rank = i + 10

		array = append(array, tmp)
	}

	b, err := json.Marshal(&array)

	if err != nil {
		log.Println(err)

	}
	os.Stdout.Write(b)
}


2min23 for sql

Hi Samuel,

How to combine increment number with for col.Next in golang?
for example like this
$offset = isset($_GET[‘offset’]) && $_GET[‘offset’] != ‘’ ? $_GET[‘offset’] : 0;
$all = mysql_query(“SELECT * FROM news ORDER BY id DESC”);
$count_all = mysql_num_rows($all);
$query = mysql_query(“SELECT * FROM news ORDER BY id DESC LIMIT $offset,10”);
$count = mysql_num_rows($query);
$json_kosong = 0;
if($count<10){
if($count==0){
$json_kosong = 1;
}else{
$query = mysql_query(“SELECT * FROM news ORDER BY id DESC LIMIT $offset,$count”);
$count = mysql_num_rows($query);
if(empty($count)){
$query = mysql_query(“SELECT * FROM news ORDER BY id DESC LIMIT 0,10”);
$num = 0;
}else{
$num = $offset;
}
}
} else{
$num = $offset;
}
$json = ‘[’;
while ($row = mysql_fetch_array($query)){
$num++;
$char =’"’;
$tgl = date(“d M Y”, strtotime($row[‘date’]));
$string = substr(strip_tags($row[‘value’]), 0, 200);
$json .= ‘{
“no”: ‘.$num.’,
“id”: "’.str_replace($char,’',strip_tags($row['id'])).'", "judul": "'.str_replace($char,'’,strip_tags($row[‘title’])).’",
“tgl”: “’.str_replace($char,’',strip_tags($tgl)).'", "isi": "'.str_replace($char,'’, $string.” …").’",
“gambar”: “’.str_replace($char,’`’,strip_tags($row[‘images’])).’”},’;
}
$json = substr($json,0,strlen($json)-1);
if($json_kosong==1){
$json = ‘[{ “no”: “”, “id”: “”, “judul”: “”, “tgl”: “”, “isi”: “”, “gambar”: “”}]’;
}else{
$json .= ‘]’;
}
echo $json;
mysql_close($connect);

In fact it is simpler by making a foreach.
For the bdd, I very often use an orm: Gorm

package main

import (
	"encoding/json"
	"log"
	"os"
	"github.com/jinzhu/gorm"
)

type Product struct {
	Rank     int
	Prodkid  int
	Produknm string
}

// QueryAll c
func (p *Product) QueryAll() []*Product {
	db, err := gorm.Open("mysql", "./gorm.db")
	if err != nil {
		log.Println(err)
	}
	defer db.Close()

	product := []*Product{}

	db.Find(&product)

	return product
}

func main() {

	var array []*Product

	// This is equivalent of return query mysql
	// test := []*Product{
	// 	&Product{
	// 		Rank:     5,
	// 		Prodkid:  4646,
	// 		Produknm: "l5zrf56r7ef",
	// 	},
	// 	&Product{
	// 		Rank:     10,
	// 		Prodkid:  13216654,
	// 		Produknm: "654fre6g4t",
	// 	},
	// }

	// Else in sql
	p := Product{}

	// product return []*Product
	product := p.QueryAll()

	// for key, value := range test {
	for _, value := range product {
		tmp := &Product{}
		tmp.Prodkid = value.Prodkid
		tmp.Produknm = value.Produknm
		tmp.Rank = value.Rank

		array = append(array, tmp)

	}

	b, err := json.Marshal(&array)

	if err != nil {
		log.Println(err)

	}
	os.Stdout.Write(b)
}

Sorry for my English. I’m French.
I hope to be understanding in my explanations

Hi Samuel,

Thanks for your quick response, and thanks for your inspiring code, i have solved it with a different approach :slight_smile:

Can i ask one more? how could changes json array to json object in golang?in a simple word how could delete the bracket in front json data?
and for example below :

[
{
“Userid”: “baskara8”,
“Username”: “Riva Ananta Baskara”,
“Email”: "brockbask@gmail.com",
“Jekel”: “L”,
“Foto”: “logo.jpg”,
“Oldpass”: “ef54c858c86afcb4cf563f1fbea74bb1bae0bb2d”
}
]

Hi Riva,

package main

import (
	"encoding/json"
	"fmt"
)

type User struct {
	Userid   string
	Username string
	Email    string
	Jekel    string
	Foto     string
	Oldpass  string
}

func main() {

	j := []byte(`[{
			"Userid": "baskara8",
			"Username": "Riva Ananta Baskara",
			"Email": "brockbask@gmail.com",
			"Jekel": "L",
			"Foto": "logo.jpg",
			"Oldpass": "ef54c858c86afcb4cf563f1fbea74bb1bae0bb2d"
			}]`)

	// b => Byte of json.Marshal to example before
	var obj []*User
	json.Unmarshal(j, &obj)

	for _, v := range obj {
		fmt.Println(v.Oldpass, v.Username, v.Userid, v.Email, v.Foto, v.Jekel)
	}

}

I hope this will suit you

Hi Samuel,

Sorry for late response, ok solved it :slight_smile:
thank you very much to teach me another angle from golang…

You’re welcome

Hi Samuel,

I want to implode every single word in phrase to loop search .
I have created in PHP like this and How in golang code?

$searchTerms = explode(’ ', $bucketsearch);
$searchTermBits = array();
foreach ($searchTerms as $term) {
$term = trim($term);
if (!empty($term)) {
$searchTermBits[] = “bucketname LIKE ‘%$term%’”;
}
}

$result = mysql_query("SELECT * FROM buckets WHERE “.implode(’ AND ', $searchTermBits).”);

Regards,
Riva

You may be looking for strings.Split and strings.Join.

But what it looks like you’re doing, building raw SQL from what is presumably user input, is dangerous and not a good idea. You should use prepared statements or you’ll have opened the door for an SQL injection attack.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.