[WEB] 라이브러리

HyeJi9908·2022년 10월 4일
0

[WEB] 기초

목록 보기
6/8

📚 직접 라이브러리 생성 및 활용

: 맨 위의 php에서 mysql 테이블 데이터 조회부분이 중복되어 그 부분만 따로 lib/db.php에 작성(config/config.php파일은 $config배열에 대해 정의한 파일) -> 중복을 줄이고 재사용을 늘리기!

-- lib/db.php

<?php
function db_init($host, $duser, $dpw, $dname){
  $conn = mysqli_connect($host, $duser, $dpw);
  mysqli_select_db($conn, $dname);
  return $conn;
}
?>

-- config/config.php
: $config배열 정의

<?php
  $config = array(
    "host" => "localhost",
    "duser" => "root",
    "dpw" => "111111",
    "dname" => "opentutorials"
  );
 ?>

-- index.php

<?php
	// mysql 테이블의 데이터 조회

	require("config/config.php"); // $config배열을 정의한 파일
	require("lib/db.php"); // 라이브러리
	$conn = db_init($config["host"], $config["duser"], $config["dpw"], $config["dname"]);
	$result = mysqli_query($conn, "SELECT * FROM topic");

 ?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<link rel="stylesheet" type="text/css" href="http://localhost/style.css">

</head>
<body id = 'target'>
	<header>
		<h1><a href="http://localhost/">JavaScript</a></h1>
		<img src="https://s3.ap-northeast-2.amazonaws.com/opentutorials-user-file/course/94.png" alt="생활코딩 이미지">
	</header>
	<nav>
		<ol>
			<?php
			// mysql 테이블의 데이터 출력

			while($row = mysqli_fetch_assoc($result)){ # 자바의 Scanner.hasNextLine()과 같은 역할,
				# $row가 null이 아니라면 반복

				echo '<li><a href="http://localhost/index.php?id='.$row['id'].'">'.$row['title'].'</a></li>'."\n";


			// $row = mysqli_fetch_assoc($result); # 변수 row에 result의 데이터중에서 첫번째 행의 데이터만을 연관배열의 형식으로 할당
			// echo $row['id'];
			// echo $row['title'];
			// echo "<br/>"; 줄 한 칸 공백
			}
			 ?>
		</ol>
	</nav>
	<div id = "control">
		<input type="button" value="white" onclick="document.getElementById('target').className='white'"/>
		<input type="button" value="black" onclick="document.getElementById('target').className='black'"/>
		<a href="http://localhost/write.php">쓰기</a>
	</div>
	<article>
	<?php
	// 맨 뒤 주소의 id 에 따라 mysql의 id에 따른 데이터 출력
	if(empty($_GET['id'])===false){
		// user 테이블과 topic테이블에서 필요한 칼럼들 가져오기
		$sql = "SELECT topic.id,title,name,description FROM topic LEFT JOIN user ON topic.author = user.id WHERE topic.id=".$_GET['id'];

		$result = mysqli_query($conn,$sql); // 만든 쿼리를 접속한 데베서버로 전송?
		$row = mysqli_fetch_assoc($result); // 해당 행 데이터

		echo '<h2>'.htmlspecialchars($row['title']).'</h2>';
      echo '<p>'.htmlspecialchars($row['name']).'</p>';
      echo strip_tags($row['description'], '<a><h1><h2><h3><h4><h5><ul><ol><li>');
	}
	?>
	</article>
</body>
</html>

-- write.php

<?php
	// mysql 테이블의 데이터 조회

	require("config/config.php");
	require("lib/db.php");
	$conn = db_init($config["host"], $config["duser"], $config["dpw"], $config["dname"]);
	$result = mysqli_query($conn, "SELECT * FROM topic");
 ?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<link rel="stylesheet" type="text/css" href="http://localhost/style.css">

</head>
<body id = 'target'>
	<header>
		<h1><a href="http://localhost/">JavaScript</a></h1>
		<img src="https://s3.ap-northeast-2.amazonaws.com/opentutorials-user-file/course/94.png" alt="생활코딩 이미지">
	</header>
	<nav>
		<ol>
			<?php
			// mysql 테이블의 데이터 출력

			while($row = mysqli_fetch_assoc($result)){ # 자바의 Scanner.hasNextLine()과 같은 역할,
				# $row가 null이 아니라면 반복

				echo '<li><a href="http://localhost/index.php?id='.$row['id'].'">'.$row['title'].'</a></li>'."\n";


			// $row = mysqli_fetch_assoc($result); # 변수 row에 result의 데이터중에서 첫번째 행의 데이터만을 연관배열의 형식으로 할당
			// echo $row['id'];
			// echo $row['title'];
			// echo "<br/>"; 줄 한 칸 공백
			}
			 ?>
		</ol>
	</nav>
	<div id = "control">
		<input type="button" value="white" onclick="document.getElementById('target').className='white'"/>
		<input type="button" value="black" onclick="document.getElementById('target').className='black'"/>
		<a href="http://localhost/write.php">쓰기</a>
	</div>
	<article>
		<form action="process.php" method="post">
			<p>
				제목:<input type="text" name="title">
			</p>
			<p>
				작성자: <input type="text" name="author">
			</p>
			<p>
				본문: <textarea name="description"></textarea>
			</p>
			<input type="submit" name="name">
		</form>
	</article>
</body>
</html>

-- process.php

<?php
require("config/config.php");
require("lib/db.php");
$conn = db_init($config["host"], $config["duser"], $config["dpw"], $config["dname"]);
$result = mysqli_query($conn, "SELECT * FROM topic");

$title = mysqli_real_escape_string($conn,$_POST['title']);
$author = mysqli_real_escape_string($conn,$_POST['author']);
$description = mysqli_real_escape_string($conn,$_POST['description']);

$sql = "SELECT * FROM user WHERE name='".$author."'";
$result = mysqli_query($conn,$sql);

if($result -> num_rows == 0){ # user테이블에 데이터가 없다면(서버로부터 전송된 데이터가 없다면) name추가해주기
  $sql = "INSERT INTO user (name,password)VALUES('".$author."'.'111111')";
  mysqli_query($conn,$sql); # 데베에 데이터 전송
  $user_id = mysqli_insert_id($conn); # 방금 추가한 데이터의 id값 알아내기
}
else{
  $row = mysqli_fetch_assoc($result);
  //var_dump($row); # 변수값 정보 출력 : array(3) { ["id"]=> string(1) "1" ["name"]=> string(6) "egoing" ["password"]=> string(6) "111111" }
  $user_id = $row['id'];
}
//exit; # 프로그램 중지

# sql에 form에서 작성한 데이터를 topic 테이블에 저장시키기
$sql = "INSERT INTO topic (title,description,author,created) VALUES('".$title."', '".$description."', '".$user_id."', now())";
$result = mysqli_query($conn,$sql); # 변수result에 db조회 데이터 할당
header('Location: http://localhost/index.php'); // location주소로 돌아가기
 ?>

📚 다른 사람의 라이브러리 활용

0개의 댓글