사자자리

[PHP & MySQL] 테이블에서 데이터를 가져와서 PHP에서 활용하기 본문

웹기초/생활코딩 WEB 3 - PHP & MySQL

[PHP & MySQL] 테이블에서 데이터를 가져와서 PHP에서 활용하기

renne 2022. 8. 3. 21:53

데이터베이스에서 데이터를 가져와서 PHP에서 활용하기: SELECT

 - 데이터베이스와 PHP는 완전히 다른 기술이기 때문에, 데이터를 PHP 데이터타입으로 전환하는 과정이 필요하다.

 

mysqli_fetch_[전환할 데이터타입]( )

1. mysqli_fetch_array를 통해 데이터를 array 형식으로 가져온다.

MariaDB [opentutorials]> SELECT * FROM topic;
+----+------------+-------------------+---------------------+
| id | title      | description       | created             |
+----+------------+-------------------+---------------------+
|  4 | MySQL      | MySQL is ...      | 2022-08-01 23:23:34 |
|  5 | Oracle     | Oracle is ...     | 2022-08-01 23:24:00 |
|  6 | SQL Server | SQL Server is ... | 2022-08-01 23:24:17 |
|  7 | MongoDB    | MongoDB is ...    | 2022-08-01 23:24:31 |
+----+------------+-------------------+---------------------+
4 rows in set (0.001 sec)
<!--htdocs\select.php-->
<?php
$conn = mysqli_connect('localhost', 'root', '021103', 'opentutorials');	//데이터베이스 서버 접속
$sql = "SELECT * FROM topic";	//topic 테이블의 모든 데이터 가져오기
$result = mysqli_query($conn, $sql);
print_r(mysqli_fetch_array($result));	//가져온 데이터를 array 형식으로 전환
?>

 

2. 데이터 중 첫 번째 행만을 보여준다. 값들은 [값의 자리수]와 [column명] 2가지 방식으로 나온다.

 

3. [값의 자리수]와 [column명]을 인덱스로 사용할 수 있다.

<!--htdocs\select.php-->
<?php
$conn = mysqli_connect('localhost', 'root', '021103', 'opentutorials');
$sql = "SELECT * FROM topic";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
echo $row[0];	//select.php 웹페이지에 4 출력
?>

 

4. 실습

<!--htdocs\select.php-->
<?php
$conn = mysqli_connect('localhost', 'root', '021103', 'opentutorials');
$sql = "SELECT * FROM topic WHERE id = 5";	//WHERE로 데이터를 가져올 행을 지정
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);

echo '<h1>'.$row['title'].'</h1>';
echo '<p>'.$row['description'].'</p>';
?>

 

5. mysqli_fetch_[전환할 데이터타입]( )의 특징

 - 실행될 때마다 $result가 가리키는 $sql문의 결과를 차례로 하나씩 return한다.

 - 더 가져올 데이터가 없으면 아무것도 출력되지 않는다(NULL).

<!--htdocs\select.php-->
<?php
$conn = mysqli_connect('localhost', 'root', '021103', 'opentutorials');
$sql = "SELECT * FROM topic";
$result = mysqli_query($conn, $sql);

$row = mysqli_fetch_array($result);	//1번 실행
echo '<h1>'.$row['title'].'</h1>';
echo '<p>'.$row['description'].'</p>';

$row = mysqli_fetch_array($result);	//2번 실행
echo '<h1>'.$row['title'].'</h1>';
echo '<p>'.$row['description'].'</p>';

$row = mysqli_fetch_array($result);	//3번 실행
echo '<h1>'.$row['title'].'</h1>';
echo '<p>'.$row['description'].'</p>';
?>

 

6. PHP에서 NULL == false이다.

<!--htdocs\select.php-->
<?php
$conn = mysqli_connect('localhost', 'root', '021103', 'opentutorials');
$sql = "SELECT * FROM topic";
$result = mysqli_query($conn, $sql);

while($row = mysqli_fetch_array($result)){	//모든 행이 실행된다. 더이상 데이터가 없으면 false가 return되므로 멈춘다.
  echo '<h1>'.$row['title'].'</h1>';
  echo '<p>'.$row['description'].'</p>';
}
?>

 

7. 데이터의 title들을 목차로 만들기

<!--htdocs\index.php-->
<?php
//title을 목차로 만들기
$conn = mysqli_connect('localhost', 'root', '021103', 'opentutorials');
$sql = "SELECT * FROM topic";
$result = mysqli_query($conn, $sql);
$list = '';
while($row = mysqli_fetch_array($result)){
  $list = $list."<li><a href=\"index.php?id={$row['id']}\">{$row['title']}</a></li>";
}
//기본적인 상태
$article = array(
  'title'=>'Welcome',
  'description'=>'Hello, WEB'
);
//id값이 있을 때, 즉 목차를 클릭했을 때 description을 불러오기
if(isset($_GET['id'])){
  $sql = "SELECT * FROM topic WHERE id={$_GET['id']}";
  $result = mysqli_query($conn, $sql);
  $row = mysqli_fetch_array($result);
  $article['title'] = $row['title'];
  $article['description'] = $row['description'];
}
?>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>WEB</title>
  </head>
  <body>
    <h1><a href="index.php">WEB</a></h1>
    <ol>
      <?=$list?>
    </ol>
    <a href="create.php">create</a> <!--글쓰기 기능 링크-->
    <h2><?=$article['title']?></h2>
    <?=$article['description']?>
  </body>
</html>
<!--htdocs\create.php-->
<?php
//title을 목차로 만들기
$conn = mysqli_connect('localhost', 'root', '021103', 'opentutorials');
$sql = "SELECT * FROM topic";
$result = mysqli_query($conn, $sql);
$list = '';
while($row = mysqli_fetch_array($result)){
  $list = $list."<li><a href=\"index.php?id={$row['id']}\">{$row['title']}</a></li>";
}
//기본적인 상태
$article = array(
  'title'=>'Welcome',
  'description'=>'Hello, WEB'
);
//id값이 있을 때, 즉 목차를 클릭했을 때 description을 불러오기
if(isset($_GET['id'])){
  $sql = "SELECT * FROM topic WHERE id={$_GET['id']}";
  $result = mysqli_query($conn, $sql);
  $row = mysqli_fetch_array($result);
  $article['title'] = $row['title'];
  $article['description'] = $row['description'];
}
?>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>WEB</title>
  </head>
  <body>
    <h1><a href="index.php">WEB</a></h1>
    <ol>
      <?=$list?>
    </ol>
    <a href="create.php">create</a> <!--글쓰기 기능 링크-->
    <h2>Create</h2>
    <form action="process_create.php" method="post">
      <p><input type="text" name="title" placeholder="title"></p>
      <p><textarea name="description" placeholder="description"></textarea></p>
      <p><input type="submit"></p>
    </form>
  </body>
</html>

Comments