웹개발/php+javascript

[php+javascript] 이미지 슬라이더 만들기(db)

RBWSN 2016. 4. 13. 09:05
728x90



먼저 기본적인 뷰는 이렇다.
post문으로 db에 추가해서 밑의 슬라이드에서 가져올수 있도록한다.

먼저 db에 파일을 추가할수 있도록 해본다.

1
2
3
4
5
6
7
8
9
10
11
 
    <div class="top_wrap">
        <div>
            <form method="post" action="img_project.php" enctype="multipart/form-data">
                <div>이미지 선택 : <input type="file" name="filename"/></div>
                <div>삽입문구 : <input type="text" name="text1"></div>
                <div><input type="submit" name="ok" value="Upload"></div>
            </form>
        </div>
    </div>
    <!-- 탑끝-->
cs


중요한거는 폼에서의 파일을 받아야하므로 enctype를 multipart로 넣어준고 post로 보내게 된다.
그리고는 만약 submit을 클릭하였다면

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 
 
<?php
 
if ($_POST['ok'== 'Upload') {
 
    $result_3 = mysqli_query($db_conn'select * from img');
    if ($_FILES) { // 파일 업로드
        $name = $_FILES['filename']['name'];
        $text = $_POST['text1'];
        if ($name == "") {
            echo "<script>alert('파일이 없습니다.');</script>";
        }
 
        while ($result_row = mysqli_fetch_row($result_3)) { // 파일명 확인
            if ($name == $result_row[1]) {
                echo "<script>alert('벌써 가지고있는 파일입니다. 파일명을 변경해주세요')</script>";
                exit;
            }
        }
        mysqli_query($db_conn"insert into img(img_name, img_text) VALUES ('$name','$text') "); // insert구문
        move_uploaded_file($_FILES['filename']['tmp_name'], $name); // 파일업로드
        echo "<script>alert('등록완료')</script>";
    }
}
 
 
?>
cs


이렇게 db를 연결하고 쿼리를 보내주어 추가를 시킨다.

$db_conn은 db를 연결하는 변수로써

$db_conn mysqli_connect($db_hostname$db_username$db_password$db_nameor die("db연결확인");
db연결을 해준다. 인자는 자신의 db에맞게 넣어준다. 그후 query를 쿼리를 날려준다.


파일이 없거나 가지고있는 파일명이라면 파일명을 변경해달라고 요청한다.
그리고는 마지막에 insert 구문으로 추가시켜준다


이미지 슬라이드 구문

먼저 이미지 슬라이드를 뿌릴 준비를한다.

3가지가 필요한데
첫번째는 이미지 파일
두번째는 삽입문구
세번째는 버튼이다.

db에 연결해서 정보들을 받아 오도록한다.

1
2
3
4
5
 
$result_1 = mysqli_query($db_conn, 'select * from img');
$result_2 = mysqli_query($db_conn, 'select * from img');
$result_3 = mysqli_query($db_conn, 'select * from img');
$result_4 = mysqli_query($db_conn, 'select * from img');
cs

먼저 db쿼리를 받아오는 변수를 설정한다.

그리고는 ui를 추가한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
    <div class="body_wrap">
        <div class="img_file">
            <?php
            $i = 0;
            while ($result_row = mysqli_fetch_row($result_1)) {
 
                $name = $result_row[1];
                echo "<img class='slide_img' src=$name data-index=$i />";
                $i++;
            }
            ?>
 
        </div>
        <div class="text_file">
            <?php
            $i = 0;
            while ($result_row = mysqli_fetch_row($result_2)) {
                $text = $result_row[2];
                echo "<div class='img_text'  data-index=$i ><h1>$text</h1> </div>";
                $i++;
            }
            ?>
        </div>
 
        <div class="control_file">
            <?php
            $i = 0;
            while ($result_row = mysqli_fetch_row($result_4)) {
                $text = $result_row[0];
                echo "<div class='img_button'  data-index=$i > </div>";
                $i++;
            }
            ?>
        </div>
    </div>
 
cs



첫div는 이미지 파일을 가져오는 쿼리
두번째는 텍스트
3번째는 id와 버튼을 추가한다.

슬라이드의 크기는 1000px며 css파일을 설정해야한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.body_wrap { position:relative; top:150px; left:15px; width:970px; height:500px; overflow:hidden}
.body_wrap{background-color:gray}
 
.img_file{width:5000px;position:relative}
.slide_img { float:left; width:1000px; height:500px;}
 
.text_file{position:absolute; top:300px; left:50px;}
.img_text{position:absolute; width:450px; height:500px;}
 
.control_file{position:absolute; top:480px; left:440px; height:13px; overflow:hidden}
.img_button{width:12px; height:46px; position:relative;float:left; cursor:pointer; background:url("point_button.png");}
 
.img_button:hover{top: -16px;}
.img_button:active{top: -31px;}
 
.active{width:12px; height:46px; position:relative; top:-30px;float:left; cursor:pointer; background:url("point_button.png");}
cs

먼저 1000px안에서 넘어가면안되므로 overflow 히든을 주어 밖의 사진들은 숨기게 만들었다.

그리고 active의 클래스css를 추가하여 사진이 올라오게되면 그에맞는 index를 찾아 파란색 불빛으로 보이게 하였다.

이제는 자바스크립트로 슬라이드 효과를 주어야한다.


자바스크립트의 파일은 이렇게되어있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  <script type="text/javascript">
        $(document).ready(function () {
            function img_slider(index) {
 
                $willMoveLeft = -(index * 1000);
                $('.img_file').animate({left: $willMoveLeft}, 'slow');
 
                $('.img_button[data-index=' + index + ']').addClass('active');
                $('.img_button[data-index!=' + index + ']').removeClass('active');
 
                $('.img_text[data-index=' + index + ']').show().animate({left: 0}, 'slow');
                $('.img_text[data-index!=' + index + ']').hide();
            }
 
            $ramdom_img = Math.round(Math.random() *
                <?php $i = 0;
               while ($result_row = mysqli_fetch_row($result_5)) {
                   $i++;
               }
               echo $i;
                ?>
            );
 
            img_slider($ramdom_img);
        });
 
 
    </script>
cs


먼저 img slider라는 함수로 index로 인자를 받는 함수를 만들었다.
먼저 사진을 랜덤으로 출력해야 하므로  while문 db에서받아와 echo 로 db의 갯수를 알아왔따
그리고 img_slider을 호출하게되는데 인자를 테이블갯수의 랜덤한 인자로 받았다.

함수안을 살펴보면 먼저 사진의 치작점을 찾아야하므로 -(index * 1000(px))로 시작점을 찾았다.
그리고는 이미지파일에 animate를 느리게 출력시키고

아까 버튼에서 돌린 data-index가 index가 맞다면 active클래스를 추가시킨다.
아닌라면 active 클래스를 삭제시킨다.

그리고 삽입문구의 인덱스를 찾아 show로 보여준다. 
이렇게 완성이 되었다면




이렇게 완성이 될것이다.

만약 클릭되어서 사진이 넘어가게하려면 이런식으로 자바스크립트 코드를 만든다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
    <script type="text/javascript">
        function img_slider(index) { // 화면 뿌려주기
            $willMoveLeft = -(index * 1000);
            $('.img_file').animate({left: $willMoveLeft}, 'slow');
            $('.img_button[data-index=' + index + ']').addClass('active');
            $('.img_button[data-index!=' + index + ']').removeClass('active');
            $('.img_text[data-index=' + index + ']').show().animate({left: 0}, 'slow');
            $('.img_text[data-index!=' + index + ']').hide();
        }
        function on_button(index) { // 이미지 슬라이더 클릭
            img_slider(index);
        }
        $(document).ready(function () { // 초기화면 설정
            $ramdom_img = Math.round(Math.random() *
                <?php $i = 0;
               while ($result_row = mysqli_fetch_row($result_5)) {
                   $i++;
               }
               echo $i;
                ?>
            );
            img_slider($ramdom_img);
        });
 
 
    </script>
cs


그리고 버튼에 on_button 을 연결해준다.

1
2
3
4
5
6
7
8
            <?php
            $i = 0;
            while ($result_row = mysqli_fetch_row($result_4)) {
                $text = $result_row[0];
                echo "<div class='img_button'  data-index=$i onclick='on_button($i);' > </div>";
                $i++;
            }
            ?>
cs


이렇게 짜면 이제 버튼클릭시 넘어가도록 설정이 된다.

728x90

'웹개발 > php+javascript' 카테고리의 다른 글

php apache(서버) mysql(db) 연동 (window)  (0) 2016.04.03