<?php
$link=mysqli_connect("localhost","root","비번", "wow" );
if (!$link)
{
echo "MySQL 접속 에러 : ";
echo mysqli_connect_error();
exit();
}
mysqli_set_charset($link,"utf8");
$sql="select * from test";
$result=mysqli_query($link,$sql);
$data = array();
if($result){
while($row=mysqli_fetch_array($result)){
array_push($data,
array('name'=>$row[1],
'age'=>$row[2]
));
}
//echo "<pre>"; print_r($data); echo '</pre>';
header('Content-Type: application/json; charset=utf8');
$json = json_encode($data, JSON_PRETTY_PRINT+JSON_UNESCAPED_UNICODE);
echo $json;
//echo json_encode($data);
}
else{
echo "SQL문 처리중 에러 발생 : ";
echo mysqli_error($link);
}
mysqli_close($link);
?>
import UIKit
struct Info:Decodable {
let name: String
let age: String
}
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var aa: UITableView!
var datalist = [Info]()
override func viewDidLoad() {
super.viewDidLoad()
let jsonUrlString = "http://127.0.0.1/wow.php"
guard let jsonURL = URL(string:jsonUrlString) else {
return
}
URLSession.shared.dataTask(with: jsonURL, completionHandler: {(
data,response,error) -> Void in
guard let data = data else{return}
do{
//백그라운드 스레드에서 작동하는 코드
self.datalist = try JSONDecoder().decode([Info].self, from: data)
print(self.datalist)
//백그라운드에서 메인(뷰)으로 접근할 수 없다.
//self.mainTableView.reloadData()
DispatchQueue.main.async(execute: {
self.aa.reloadData()
})
}catch{
print("parsing error\(error)")
}
}).resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datalist.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! MyTableViewCell
let structTemp = datalist[indexPath.row]
cell.name.text = structTemp.name
cell.age.text = structTemp.age
return cell
}
}
//
// MyTableViewCell.swift
// Relax
//
// Created by MacBookPro on 2017. 12. 19..
// Copyright © 2017년 MacBookPro. All rights reserved.
//
import UIKit
class MyTableViewCell: UITableViewCell {
@IBOutlet weak var name: UILabel!
@IBOutlet weak var age: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
// 20171219104719
// http://localhost/wow.php
[
{
"name": "kang",
"age": "12"
},
{
"name": "kim",
"age": "40"
},
{
"name": "hong",
"age": "80"
},
{
"name": "sung",
"age": "30"
}
]
php에서 화면단으로 가져오기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>crud</title>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery-3.1.1.min.js"> </script>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<style>
body{
margin:0;
padding:0;
background-color:#f1f1f1;
}
.box{
width:750px;
padding:20px;
background-color:#fff;
border:1px solid #ccc;
border-radius:5px;
margin-top:100px;
}
</style>
</head>
<body>
<div class="container box">
<h3 align="center">php Ajax Crud</h3>
<br/><br/>
<br/><br/>
<label>성을 입력하세요</label>
<input type="text" name="first_name" id="first_name" class="form-control" />
<br/>
<label>이름을 입력하세요</label>
<input type="text" name="last_name" id="last_name" class="form-control" />
<br/><br/>
<div align="center">
<!-- 클릭했을 때 user id를 알 수 있게 숨겨 둔다.-->
<input type="hidden" name="id" id="user_id" />
<button type="button" name="action" id="action" class="btn btn-warning">추가</button>
</div>
<br/><br/>
<!-- ++++++++++++++++++결과 리스트 출력 테이블++++++++++++++++++++++++ -->
<!-- select.php에서 받아온 데이터를 이곳에다가 붙인다. -->
<div id="result" class="table-responsive">
</div>
</div>
</body>
<script>
$(document).ready(function(){
fetchUser();
function fetchUser()
{
//[1] users 리스트를 select.php 에서 받아온다.
$.ajax({
url:"wow.php",
method:"POST",
dataType:"json",
success:function(data){
//$('#first_name').val('');
//$('#last_name').val('');
//$('#action').text("추가");
//$('#result').html(data);
//alert(data[0].name)
//var jsonstr = JSON.stringify(data) //객체를 문자열로
//var contact = JSON.parse(jsonstr); //문자열을 객체로
//alert(typeof data); //object
//alert(typeof(JSON.stringify(data)));//string
var str = "";
$.each(data,function(idx, json){
str+= json.name+ ":" + json.age+"</br>"
})
document.write(str)
},
error: function(request, status, error){
alert(request);
alert(status);
alert(error);
}
})
}
//[2] 추가 버튼 클릭했을 때 작동되는 함수
$('#action').click(function(){
//각 엘리먼트들의 데이터 값을 받아온다.
var a = $('#first_name').val();
var b = $('#last_name').val();
//성과 이름이 올바르게 입력이 되면
if(a !='' && b != ''){
$.ajax({
//insert page로 위에서 받은 데이터를 넣어준다.
url:"wow4.php",
method:"POST",
data:{a:a,b:b},
success:function(data){
//성공하면 action.php 에서 출력된 데이터가 넘어온다.
alert(data);
}
});
}else
{
alert('빈칸을 입력해 주세요');
}
});
});
</script>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
댓글