前提・実現したいこと
php経由でデータベースから取得したデータをswiftを使ってtableviewに一覧表示させたいです。
以下に記載されてるMySQLのデータ内のlidの列に保存されてるデータをswiftのテーブルビューに表示させたいです。
下に画像を載せましたが、プログラムを実行するとテーブルビューの部分が真っ白になって何も出てきません。
テーブルビューのコードの辺りがおかしいのか、JSONデータを解析する所あたりで間違っているのか、よくわからなくて困っております。
解決方法をご教示頂ければ幸いです。
エラーメッセージはありません。
該当のソースコード
swift
import UIKit class CourseViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { let URL_COURSE_DATA = "https://hogehoge/dbApi.php" var courses: [String] = [] var sid:String! = "000" override func viewDidLoad() { super.viewDidLoad() let requestURL = NSURL(string: URL_COURSE_DATA) let request = NSMutableURLRequest(url: requestURL! as URL) request.httpMethod = "POST" let postParameters = "sid="+sid!; request.httpBody = postParameters.data(using: String.Encoding.utf8) let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in if error != nil { print("error is (error!)") return; } do { let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String:[String:String]] if let parseJSON = myJSON { for (key, value) in parseJSON { print(key) for (key2, value2) in value{ print(key2) self.courses.append(value2) } } } }catch{ print(error) } } task.resume() // Do any additional setup after loading the view. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return courses.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // セルを取得する let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "coursecell", for: indexPath) // セルに表示する値を設定する cell.textLabel!.text = courses[indexPath.row] return cell }
PHP
<?php //dbApi.php //dbOperation.phpは下に記載してあります。 $response = array(); if($_SERVER['REQUEST_METHOD']=='POST'){ $sid = $_POST['sid']; require_once 'dbOperation.php'; $db = new dbOperation(); if($db->selectSQL($sid)){ $response = $db->selectSQL($sid)->fetchAll(); }else{ $response['error'] = true; } }else{ $response['error'] = true; } echo json_encode($response); ?>
PHP
<?php //dbOperation.php //config.phpにはデータベース名やデータベースhostの設定を記述 //dbConnect.phpにはPDOでの接続処理を記述 class dbOperation{ private $conn; function __construct(){ require_once 'config.php'; require_once 'dbConnect.php'; $db = new dbConnect(); $this->conn = $db->connect(); } public function selectSQL($sid){ $sql = "select lid from course where sid = ?"; $result = $this->conn->prepare($sql); $result->execute(array($sid)); return $result; } } ?>
MySQL
sid | lid 000 | hogehoge 000 | hagehage 000 | hugehuge
試したこと
テーブルビューのデリゲートやデータソースのアウトレットは紐付けました。
補足情報(FW/ツールのバージョンなど)
最終的にMySQLのlidに格納されてるhogehogeとかの一覧をテーブルビューで表示したいです。
実行したらテーブルビューの部分が真っ白くなって何も出てきません。
まだ回答がついていません
会員登録して回答してみよう