I have these PHP file to fetch data from database based on "dept" condition.
getDeptList.php
<?php
if (isset($_POST['dept'])){
$dept = $_POST['dept'];
$sql = "SELECT * FROM users WHERE dept ='$dept'";
$result = mysqli_query($connect, $sql);
if ($result && mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result)) {
$login_db = $row['login'];
$real_namedb = $row['real_name'];
$output[]= array('login' => $login_db, 'real_name' => $real_namedb);
}
echo json_encode($output);
mysqli_free_result($result);
}
else {
$output = array('login' => 'wrong credentials from PHP code!');
echo json_encode($output);
echo mysqli_error($connect);
}
}
?>
In x code, I have value UILabel that has been set to "ITD" and this value need to be post into PHP first to produce Array output in UIPickerView.
Here's my code so far.
UPDATE
getDeptList.swift
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
@IBOutlet var deptLbl: UILabel!
@IBOutlet var loginLbl: UILabel!
@IBOutlet var real_nameLbl: UILabel!
@IBOutlet var dropdownTxt: UITextField!
@IBOutlet var dropdown: UIPickerView!
var persons = [Person]()
struct Person {
var login: String
var real_name: String
init?(dict: [String:Any]) {
guard let login = dict["login"] as? String, let real_name = dict["real_name"] as? String else {
return nil
}
self.login = login
self.real_name = real_name
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.persons.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return persons[row].real_name
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if row >= self.persons.count {
return
}
self.loginLbl.text = self.persons[row].login
self.real_nameLbl.text = self.persons[row].real_name
self.dropdown.isHidden = true
self.dropdownTxt.resignFirstResponder()
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == self.dropdownTxt {
self.dropdown.isHidden = false
}
}
func getDropdownJSON(){
deptLbl.text = "ITD"
var request = URLRequest(url: URL(string: "http://localhost/getDeptList.php")!)
request.httpMethod = "POST"
let postString = "dept=\(deptLbl.text!)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
if let result = try? JSONSerialization.jsonObject(with: data, options: []) {
print(result)
}
}
task.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
getDropdownJSON()
}
}
Console did'nt print result value
The problem is, UIPickerView can't fetch the Array output. I'm not sure why. maybe someone can help to solve this issue.
Thanks.