In php, I can print rowcount where postid matches with the code below without passing the result in a while loop.
$status_query = "SELECT count(*) as postCount FROM postData WHERE postid=1";
$status_result = mysqli_query($con,$status_query);
$status_row = mysqli_fetch_array($status_result);
$postCount = $status_row['postCount'];
echo $postCount;
Now am re-writing the code to golang for the same row count. I leverage Stackoverflow solution found here. source link
With that Stackoverflow solution link above, the golang code below is working great as I can get the row count.
rows1, err := db.Query("SELECT COUNT(*) as postCount FROM postData WHERE postid=1")
if err != nil {
log.Fatal(err)
}
defer rows1.Close()
var postCount int
for rows1.Next() {
if err := rows1.Scan(& postCount); err != nil {
log.Fatal(err)
}
}
fmt.Printf("Number of rows are %s
", postCount)
Here is what I want modify:
The above code passed the row count result within
for rows1. Next(){
// result here.
}
My question is:
Please how do I avoid this for rows.next()
function and just get my result straight since am retrieving the row count based on postid.
In php code above, I can get the result straight without passing it in a while loop.
In golang am thinking of something like the code below
rows1, err := db.Query("SELECT COUNT(*) as postCount FROM postData WHERE postid=1")
if err != nil {
log.Fatal(err)
}
defer rows1.Close()
var status_row = rows1.Next()
var postCount =rows1.Scan(& postCount)
fmt.Printf("Number of rows are %s
", postCount)
Does anyone has a better way of getting this rowcount to display straight without passing the result within for rows1.Next()
method
Here is the overall working code before I seek modification in the coding illustrations above.
package main
import "database/sql"
import _ "github.com/go-sql-driver/mysql"
import "net/http"
import "fmt"
import "log"
var db *sql.DB
var err error
func getRecordPage1(res http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
http.ServeFile(res, req, "getjsonRecord.html")
return
}
//The commented section below is the code I want to modify to avoid use of for rows.next function....
/*
rows1, err := db.Query("SELECT COUNT(*) as postCount FROM like_unlike WHERE postid=1")
if err != nil {
log.Fatal(err)
}
defer rows1.Close()
var postCount int
for rows1.Next() {
if err := rows1.Scan(& postCount); err != nil {
log.Fatal(err)
}
}
fmt.Printf("Number of rows are %s
", postCount)
}
*/
func homePage(res http.ResponseWriter, req *http.Request) {
http.ServeFile(res, req, "index.html")
}
func main() {
db, err = sql.Open("mysql", "root:@/golang44")
if err != nil {
panic(err.Error())
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err.Error())
}
http.HandleFunc("/getjsonRecord", getRecordPage1)
http.HandleFunc("/", homePage)
fmt.Println("Listening on 127.0.0.1:8088")
http.ListenAndServe(":8088", nil)
}