如何获得精确用户php mysql的所有值

时间:2017-06-29 14:15:43

标签: php mysql swift

如何获得精确用户的所有值? 我有两个表,一个用户和一个产品列表。 用户登录时,必须显示与他关联的产品列表。问题是我只得到一个产品而不是该用户的所有产品。这个php与一个带有swift的ios应用程序连接。 所以我需要在该用户的产品列表中显示所有产品。

<?php

/ **  *由PhpStorm创建。  *用户:antonio  *日期:17/06/17  *时间:20:36  * /

课程DbOperation {     私人$ conn;

//Constructor
function __construct()
{
    require_once dirname(__FILE__) . '/Constants.php';
    require_once dirname(__FILE__) . '/DbConnect.php';
    // opening db connection
    $db = new DbConnect();
    $this->conn = $db->connect();
}

//Function to create a new user
public function createUser($username, $pass, $email, $nome, $cognome, $telefono, $immagine)
{
    if (!$this->isUserExist($username, $email, $telefono)) {
        $password = md5($pass);
        $stmt = $this->conn->prepare("INSERT INTO utenti (username, password, email, nome, cognome, telefono, immagine) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssss", $username, $password, $email, $nome, $cognome, $telefono, $immagine);
        if ($stmt->execute()) {
            return USER_CREATED;
        } else {
            return USER_NOT_CREATED;
        }
    } else {
        return USER_ALREADY_EXIST;
    }
}


private function isUserExist($username, $email, $telefono)
{
    $stmt = $this->conn->prepare("SELECT id FROM utenti WHERE username = ? OR email = ? OR telefono = ?");
    $stmt->bind_param("sss", $username, $email, $telefono);
    $stmt->execute();
    $stmt->store_result();
    return $stmt->num_rows > 0;
}

public function userLogin($username, $pass)
{
    $password = md5($pass);
    $stmt = $this->conn->prepare("SELECT id FROM utenti WHERE username = ? AND password = ?");
    $stmt->bind_param("ss", $username, $password);
    $stmt->execute();
    $stmt->store_result();
    return $stmt->num_rows > 0;
}

/*
 * After the successful login we will call this method
 * this method will return the user data in an array
 * */

public function getUserByUsername($username)
{
    $stmt = $this->conn->prepare("SELECT id, username, email, nome, cognome, telefono, immagine FROM utenti WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->bind_result($id, $username, $email, $nome, $cognome, $telefono, $immagine);
    $stmt->fetch();
    $user = array();
    $user['id'] = $id;
    $user['username'] = $username;
    $user['email'] = $email;
    $user['nome'] = $nome;
    $user['cognome'] = $cognome;
    $user['telefono'] = $telefono;
    $user['immagine'] = $immagine;
    return $user;
}
public function getProdottiByUsername($username)
{
    $stmt = $this->conn->prepare("SELECT * FROM `listaprodotti` WHERE `username` = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->bind_result($username, $id_prodotto, $nome_prodotto, $categoria, $quantita);
    $stmt->fetch();
    $prodotti = array();
    $prodotti['username'] = $username;
    $prodotti['id_prodotto'] = $id_prodotto;
    $prodotti['nome_prodotto'] = $nome_prodotto;
    $prodotti['categoria'] = $categoria;
    $prodotti['quantita'] = $quantita;

    return $prodotti;
}

这是用于登录和获取值(用户和产品)的快速代码 {

导入Alamofire 导入UIKit 导入AVFoundation

类LoginController1:UIViewController {

//The login script url make sure to write the ip instead of localhost
//you can get the ip using ifconfig command in terminal
let URL_USER_LOGIN = "http://................"

//the defaultvalues to store user data
let defaultValues = UserDefaults.standard

//the connected views
//don't copy instead connect the views using assistant editor
@IBOutlet weak var labelMessage: UILabel!
@IBOutlet weak var username: UITextField!

@IBOutlet weak var password: UITextField!

//the button action function
@IBAction func buttonLogin(_ sender: UIButton) {

    //getting the username and password
    let parameters: Parameters=[
        "username":username.text!,
        "password":password.text!
    ]

    //making a post request
    Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseJSON
        {
            response in
            //printing response
            print(response)

            //getting the json value from the server
            if let result = response.result.value {
                let jsonData = result as! NSDictionary

                //if there is no error
                if(!(jsonData.value(forKey: "error") as! Bool)){

                    //getting the user from response
                    let user = jsonData.value(forKey: "user") as! NSDictionary


                    //getting user values
                    let userId = user.value(forKey: "id") as! Int
                    let userName = user.value(forKey: "username") as! String
                    let userEmail = user.value(forKey: "email") as! String
                    let userNome = user.value(forKey: "nome") as! String
                    let userCognome = user.value(forKey: "cognome") as! String
                    let userTelefono = user.value(forKey: "telefono") as! String



                    //saving user values to defaults
                    self.defaultValues.set(userId, forKey: "userid")
                    self.defaultValues.set(userName, forKey: "username")
                    self.defaultValues.set(userEmail, forKey: "useremail")
                    self.defaultValues.set(userNome, forKey: "usernome")
                    self.defaultValues.set(userCognome, forKey: "usercognome")
                    self.defaultValues.set(userTelefono, forKey: "usertelefono")


                    ///prende i valori dei prodotti dalla cella legata a quel username

                    let prodotti = jsonData.value(forKey: "prodotti") as! NSDictionary

                    let prodottiId_prodotto = prodotti.value(forKey: "id_prodotto") as! Int
                    let prodottiNome_prodotto = prodotti.value(forKey: "nome_prodotto") as! String
                    let prodottiCategoria = prodotti.value(forKey: "categoria") as! String
                    let prodottiQuantita = prodotti.value(forKey: "quantita") as! String
                    let prodottiUsername = prodotti.value(forKey: "username") as! String


                    //saving i valori di questo username
                    self.defaultValues.set(prodottiId_prodotto, forKey: "id_prodotti")
                    self.defaultValues.set(prodottiNome_prodotto, forKey: "nome_prodotto")
                    self.defaultValues.set(prodottiCategoria, forKey: "categoria")
                    self.defaultValues.set(prodottiQuantita, forKey: "quantita")
                    self.defaultValues.set(prodottiUsername, forKey: "username")

                    //Go to the HomeViewController if the login is sucessful
                    let ProfiloController = self.storyboard?.instantiateViewController(withIdentifier: "Profilo") as! ProfiloController
                    self.navigationController?.pushViewController(ProfiloController, animated: true)

                    self.dismiss(animated: false, completion: nil)

                    }else{
                                            //error message in case of invalid credential
                    let alertController = UIAlertController(title: "Error", message: "Username e password sbagliati", preferredStyle: .alert)
                    let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
                    alertController.addAction(defaultAction)

                    self.present(alertController, animated: true, completion: nil)
                    }
            }
                }
}






override func viewDidLoad() {
    super.viewDidLoad()
    if defaultValues.string(forKey: "username") != nil{
        let ProfiloController = self.storyboard?.instantiateViewController(withIdentifier: "Profilo") as! ProfiloController
        self.navigationController?.pushViewController(ProfiloController, animated: true)

    }
}


    var player: AVPlayer?
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)





    let tap = UITapGestureRecognizer(target: self, action: #selector(LoginController1.dismissKeyboard))
    view.addGestureRecognizer(tap)
    let path = Bundle.main.path(forResource: "introoiphone 7 plus", ofType: "mp4")
    player = AVPlayer(url: URL(fileURLWithPath: path!))
    player!.actionAtItemEnd = AVPlayerActionAtItemEnd.none;
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = self.view.frame
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
    self.view.layer.insertSublayer(playerLayer, at: 0)
    NotificationCenter.default.addObserver(self, selector: #selector(LoginController1.playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player!.currentItem)
    player!.seek(to: kCMTimeZero)
    player!.play()

}

func playerItemDidReachEnd() {
    player!.seek(to: kCMTimeZero)
}



func dismissKeyboard(tap: UITapGestureRecognizer) {
    print("Keyboard Dismiss Again")
    view.endEditing(true)
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

1 个答案:

答案 0 :(得分:0)

我认为你需要做一些循环的事情,比如

$UserQuery = 'YOUR_QUERY_THING_H_E_R_E';
while ($UserProducts = mysql_fetch_array($UserQuery)) {
$Products = $UserProducts["prod"]);
}

此。它在许多情况下都很简单有用。