0

I'm going to create web application using Swift. I have a problem with connection with MySQL. I use PhpMyAdmin for MySQL databases management. It seems to me that the best way is to use Perfect. I have done everything in accordance with Perfect - MySQL Connector! Unfortunately, I have a problem with calling function useMysql in main.swift. I wonder whether it is written correctly. I invoke function useMysql in file main.swift:

//This route will be used to fetch data from the mysql database
routes.add(method: .get, uri: "/use", handler: useMysql)

However in file mysql_quickstart.swift we define function with two arguments:

public func useMysql(_ request: HTTPRequest, response: HTTPResponse) 
{
//function body 
}

I am not sure but maybe I should call it in this way? -

routes.add(method: .get, uri: "/use", handler: useMysql(request: object of HTTPRequest, response: object of HTTPResponse))

I don't have any errors however function useMysql seems to be never executed. I am aware of fact that it isn't a good habit to attach code from files of project but maybe it will be useful. Here is my code Any suggestions? Thanks in advance.

I have also found other Perfect - MySQL Connector tutorial and I'm not sure which way is better? By the by I wonder if it is a good idea to use more than one framework in one project? For instance both Perfect and Kitura or Vapor, too?

EDITED: What do you think to use it in this way?

// Register your own routes and handlers
var routes = Routes()
routes.add(method: .get, uri: "/", handler: {
        request, response in
        response.setHeader(.contentType, value: "text/html")
        response.appendBody(string: "<html><title>Hello, world!</title><body>Hello, world!</body></html>")
        //This route will be used to fetch data from the mysql database
        useMysql(request, response: response)
        response.completed()
    }
)

2 Answers2

0

Two things, swap out the useMysql function with a simple print result and return HTML function.

Second, I suggest looking at (or using) the MySQL StORM abstraction layer.

https://github.com/SwiftORM/MySQL-StORM

It's quite possible it's permissions, host access or port.

Jono Guthrie
  • 213
  • 2
  • 9
0

Main.Swift:-

routes.add(method: .post, uri: "/admin/api/v1/login") { (request, response) in

let email = request.param(name: "email")
let password = request.param(name: "passwrod")
let JSON = Login.checkLogin(email: email, password: password)
do {
    try response.setBody(json: JSON)
        .completed()
} catch {
 }
}

Login.Swift

import Foundation
import PerfectMySQL
import PerfectLib

class Login: NSObject {

 class func checkLogin(email: String?, password: String?)-> JSONConvertible {

 var JSON: JSONConvertible?



 if !ServerHelper.isValidEmail(candidate: email) {

 JSON =  ServerHelper.getErrorJson(message: KMESSAGE_INVALID_EMAIL_ADDRESS)
 return JSON


 } else if !ServerHelper.isValidPassword(password: password!) {

 JSON =  ServerHelper.getErrorJson(message: KMESSAGE_INVALID_PASSWORD)
 return JSON

 } else {


 let mySql = MySQL()
 let connect =  mySql.connect(host: "127.0.0.1", user: "root", password: "mypassword", db:"SuperAdmin" , port: 3306, socket: "", flag: 0)
 if !connect {

 JSON =  ServerHelper.getErrorJson(message: KMESSAGE_SERVER_ERROR)
 return JSON
 }

 let query = "select email, phone_number from SuperAdmin.Login where email='\(String(describing: email!))' AND password='\(String(describing: password!))'"

 if mySql.query(statement: query) {

 let result = mySql.storeResults

 var jsonResult = [Dictionary<String, Any>]()

 result()?.forEachRow(callback: { (element) in

 var dict = Dictionary<String, Any>()

 if let arrRow = element as? [String] {

 let email = arrRow[0]
 let phone_number = arrRow[1]
 dict["email"] = email
 dict["phone_number"] = phone_number
 jsonResult.append(dict)
 }
 })

 if jsonResult.count == 0 {

 JSON =  ServerHelper.getErrorJson(message: KMESSAGE_NOT_AUTHORIZE)

 } else {

 JSON = ServerHelper.getJson(result: jsonResult)

 }

 } else {

 JSON =  ServerHelper.getErrorJson(message: KMESSAGE_NOT_AUTHORIZE)
 return JSON
 }
 mySql.close()
 }
 return JSON
 }


}

Hit POST API like localhost:8080/admin/api/v1/login

and I got the response:

{
"status": 200,
"succcess": true,
"result": [
    {
        "phone_number": "84747474574",
        "email": "myemail@swift.com"
    }
]


}

Please make sure your are passing correct values to connect with database

let connect =  mySql.connect(host: "127.0.0.1", user: "root", password: "mypassword", db:"SuperAdmin" , port: 3306, socket: "", flag: 0)
Deepak Singh
  • 241
  • 3
  • 11