쿼리 및 iq_id 질문입니다...

쿼리 및 iq_id 질문입니다...

QA

쿼리 및 iq_id 질문입니다...

본문

** 수정 **

음.. select 한게 없으니 그런거라 생각하고

아래의 쿼리를 실행해서 결과값을 $iq_id에 저장 했습니다.

이렇게 하는게 맞을까요!? 


if ($w == '') {
    $sql_iqid = sql_fetch("SELECT * FROM {$g5['g5_shop_item_qa_table']} ORDER BY iq_id DESC LIMIT 1");
    $iq_id = $sql_iqid['iq_id'];
}

 

** 수정 끝 **

 

일단 itemqaform,skin.php 에 파일추가 하게끔

아래의 소스를 추가해주었습니다.

그리고 g5_shop_item_qa 테이블에

qa_file 과 qa_option 필드를 추가해주었습니다

qa_file 은 파일개수를 넣는 필드구요

qa_option 은 write table 의 wr_option 과 같습니다

추후 이미지를 출력하기 위해 html1 로 지정해봤습니다(?)

 


<?php 
            $is_file = true;
            $file_count = 4;
            for ($i=0; $is_file && $i<$file_count; $i++) { 
        ?>
        <tr>
            <th scope="row">파일 #<?php echo $i+1 ?></th>
            <td>
                <input class="upload_name" value="파일선택" disabled="disabled">
                <label for="fileInput<?php echo $i; ?>" class="file_label">찾아보기</label>
                <input type="file" name="bf_file[]" title="파일첨부 <?php echo $i+1 ?> : 용량 <?php echo $upload_max_filesize ?> 이하만 업로드 가능" id="fileInput<?php echo $i; ?>" class="frm_file frm_input">
                <?php if ($is_file_content) { ?>
                <input type="text" name="bf_content[]" value="<?php echo ($w == 'u') ? $file[$i]['bf_content'] : ''; ?>" title="파일 설명을 입력해주세요." class="frm_file frm_input" size="50">
                <?php } ?>
                <?php if($w == 'u' && $file[$i]['file']) { ?>
                <input type="checkbox" id="bf_file_del<?php echo $i ?>" name="bf_file_del[<?php echo $i;  ?>]" value="1"> <label for="bf_file_del<?php echo $i ?>"><?php echo $file[$i]['source'].'('.$file[$i]['size'].')';  ?> <b>파일을 삭제하시려면 체크해주세요</b></label>
                <?php } ?>
                <script>
                    var fileTarget = $("#fileInput<?php echo $i ?>");
                    var name = '';
                    fileTarget.on('change', function(){ // 값이 변경되면 
                        if(window.FileReader){ // modern browser 
                            var filename = $(this)[0].files[0].name; 
                        } else { // old IE 
                            var filename = $(this).val().split('/').pop().split('\\').pop(); // 파일명만 추출 
                        } 
                        // 추출한 파일명 삽입 
                        $(this).siblings('.upload_name').val(filename);
                    }); 
                </script>
            </td>
        </tr>

 

 

 

그런데..

첨부파일을 넣고 질문을 남기면.

board_file 테이블에도 잘 저장이 되고,

data 폴더에도 폴더생성 및 파일 저장까지 잘됩니다.

근데 g5_shop_item_qa 테이블의 해당 게시글의 qa_file 필드는

항상 0입니다.

그래서 체크해보니

iq_id 가 항상 빈값으로 찍히더라구요..

 

근데 아래 소스 보시면 아시겠지만

새글이 insert 된 시점 이후에 iq_id를 가져다 쓰는건데..

왜 iq_id 가 빈값일까요?

 

itemqaformupdate.php 파일입니다


<?php
include_once('./_common.php');
if (!$is_member) {
    alert_close("상품문의는 회원만 작성이 가능합니다.");
}
$iq_id = (int) trim($_REQUEST['iq_id']);
$iq_subject = trim($_POST['iq_subject']);
$iq_question = trim($_POST['iq_question']);
$iq_answer = trim($_POST['iq_answer']);
$hash = trim($_REQUEST['hash']);
$device = trim($_POST['device']);
$prev_url = trim($_POST['prev_url']);
$get_editor_img_mode = $config['cf_editor'] ? false : true;
if ($w == "" || $w == "u") {
    $iq_name     = addslashes(strip_tags($member['mb_name']));
    $iq_password = $member['mb_password'];
    if (!$iq_subject) alert("제목을 입력하여 주십시오.");
    if (!$iq_question) alert("질문을 입력하여 주십시오.");
}
$itemqalist = 'itemqalist';
$mypage = 'mypage_';
/* 2018-01-16 원본 주석처리
if($is_mobile_shop)
    $url = './iteminfo.php?it_id='.$it_id.'&info=qa';
else
    $url = "./item.php?it_id=$it_id&_=".get_token()."#sit_qa";
*/
/* 2018-03-20 주석 처리 
if($is_mobile_shop) {
    if(strpos($prev_url,$itemqalist) == true) {
        if(strpos($prev_url,$mypage)){
            $url = "./mypage_itemqalist.php";    
        } else {
            $url = "./itemqalist.php"; 
        }
    } else {
        $url = "./item.php?it_id=$it_id&_=".get_token()."#itemqa"; 
    }
} else {
    if(strpos($prev_url,$itemqalist) == true) {
        if(strpos($prev_url,$mypage)){
            $url = "./mypage_itemqalist.php";    
        } else {
            $url = "./itemqalist.php"; 
        }
    } else {
        $url = "./item.php?it_id=$it_id&_=".get_token()."#itemqa"; 
    }
}
*/
// 2018-03-21 파일
$upload_max_filesize = ini_get('upload_max_filesize');
if (empty($_POST)) {
    alert("파일 또는 글내용의 크기가 서버에서 설정한 값을 넘어 오류가 발생하였습니다.\\npost_max_size=".ini_get('post_max_size')." , upload_max_filesize=".$upload_max_filesize."\\n게시판관리자 또는 서버관리자에게 문의 바랍니다.");
}

if(strpos($prev_url,$itemqalist) == true) {
    if(strpos($prev_url,$mypage)){
        $url = "./mypage_itemqalist.php";    
    } else {
        $url = "./itemqalist.php"; 
    }
} else {
    $url = "./item.php?it_id=$it_id&_=".get_token()."#itemqa"; 
}
if ($w == "")
{
    $sql = "insert {$g5['g5_shop_item_qa_table']}
               set it_id = '$it_id',
                   mb_id = '{$member['mb_id']}',
                   iq_secret = '$iq_secret',
                   iq_name  = '$iq_name',
                   iq_email = '$iq_email',
                   iq_hp = '$iq_hp',
                   iq_password  = '$iq_password',
                   iq_subject  = '$iq_subject',
                   iq_question = '$iq_question',
                   iq_time = '".G5_TIME_YMDHIS."',
                   iq_ip = '$REMOTE_ADDR',
                   device = '$device',
                   qa_option = 'html1'";
    sql_query($sql);
    $alert_msg = '1:1문의가 등록 되었습니다.';
}
else if ($w == "u")
{
    if (!$is_admin)
    {
        $sql = " select count(*) as cnt from {$g5['g5_shop_item_qa_table']} where mb_id = '{$member['mb_id']}' and iq_id = '$iq_id' ";
        $row = sql_fetch($sql);
        if (!$row['cnt'])
            alert("자신의 1:1문의만 수정하실 수 있습니다.");
    }
    $sql = " update {$g5['g5_shop_item_qa_table']}
                set iq_secret = '$iq_secret',
                    iq_email = '$iq_email',
                    iq_hp = '$iq_hp',
                    iq_subject = '$iq_subject',
                    device = '$device',
                    iq_question = '$iq_question'
              where iq_id = '$iq_id' ";
    sql_query($sql);
    $alert_msg = '1:1문의가 수정 되었습니다.';
}
else if ($w == "d")
{
    if (!$is_admin)
    {
        $sql = " select iq_answer from {$g5['g5_shop_item_qa_table']} where mb_id = '{$member['mb_id']}' and iq_id = '$iq_id' ";
        $row = sql_fetch($sql);
        if (!$row)
            alert("자신의 1:1문의만 삭제하실 수 있습니다.");
        if ($row['iq_answer'])
            alert("답변이 있는 1:1문의는 삭제하실 수 없습니다.");
    }
    // 에디터로 첨부된 이미지 삭제
    $sql = " select iq_question, iq_answer from {$g5['g5_shop_item_qa_table']} where iq_id = '$iq_id' and md5(concat(iq_id,iq_time,iq_ip)) = '{$hash}' ";
    $row = sql_fetch($sql);
    $imgs = get_editor_image($row['iq_question'], $get_editor_img_mode);
    for($i=0;$i<count($imgs[1]);$i++) {
        $p = parse_url($imgs[1][$i]);
        if(strpos($p['path'], "/data/") != 0)
            $data_path = preg_replace("/^\/.*\/data/", "/data", $p['path']);
        else
            $data_path = $p['path'];
        if( preg_match('/(gif|jpe?g|bmp|png)$/i', strtolower(end(explode('.', $data_path))) ) ){
            $destfile = ( ! preg_match('/\w+\/\.\.\//', $data_path) ) ? G5_PATH.$data_path : '';
            if($destfile && preg_match('/\/data\/editor\/[A-Za-z0-9_]{1,20}\//', $destfile) && is_file($destfile))
                @unlink($destfile);
        }
    }
    $imgs = get_editor_image($row['iq_answer'], $get_editor_img_mode);
    for($i=0;$i<count($imgs[1]);$i++) {
        $p = parse_url($imgs[1][$i]);
        if(strpos($p['path'], "/data/") != 0)
            $data_path = preg_replace("/^\/.*\/data/", "/data", $p['path']);
        else
            $data_path = $p['path'];
        if( preg_match('/(gif|jpe?g|bmp|png)$/i', strtolower(end(explode('.', $data_path))) ) ){
            $destfile = ( ! preg_match('/\w+\/\.\.\//', $data_path) ) ? G5_PATH.$data_path : '';
            if($destfile && preg_match('/\/data\/editor\/[A-Za-z0-9_]{1,20}\//', $destfile) && is_file($destfile))
                @unlink($destfile);
        }
    }
    $sql = " delete from {$g5['g5_shop_item_qa_table']} where iq_id = '$iq_id' and md5(concat(iq_id,iq_time,iq_ip)) = '{$hash}' ";
    sql_query($sql);
    $alert_msg = '1:1문의가 삭제 되었습니다.';
}

// *******************************
// ******* 2018-03-21 파일 ********
// *******************************
$bo_table = 'ItemQa';
$file_limit = 4;
$file_count = 0;
$upload_count = count($_FILES['bf_file']['name']);
for ($i=0; $i<$upload_count; $i++) {
    if ($_FILES['bf_file']['name'][$i] && is_uploaded_file($_FILES['bf_file']['tmp_name'][$i])) {
        $file_count++;
    }
}
if ($w == 'u') {
    $file = get_file('item_qa', $it_id);
    if ($file_count && (int)$file['count'] > 4){
        alert('기존 파일을 삭제하신 후 첨부파일을 '.$file_limit.'개 이하로 업로드 해주십시오.');
    }
} else {
    if($file_count > 4)
        alert('첨부파일을 '.$file_limit.'개 이하로 업로드 해주십시오.');
}
// 디렉토리가 없다면 생성합니다.
@mkdir(G5_DATA_PATH.'/file/'.$bo_table, G5_DIR_PERMISSION);
@chmod(G5_DATA_PATH.'/file/'.$bo_table, G5_DIR_PERMISSION);
$chars_array = array_merge(range(0,9), range('a','z'), range('A','Z'));
// 가변 파일 업로드
$file_upload_msg = '';
$upload = array();
for ($i=0; $i<count($_FILES['bf_file']['name']); $i++){
    $upload[$i]['file']     = '';
    $upload[$i]['source']   = '';
    $upload[$i]['filesize'] = 0;
    $upload[$i]['image']    = array();
    $upload[$i]['image'][0] = '';
    $upload[$i]['image'][1] = '';
    $upload[$i]['image'][2] = '';
    // 삭제에 체크가 되어있다면 파일을 삭제합니다.
    if (isset($_POST['bf_file_del'][$i]) && $_POST['bf_file_del'][$i]) {
        $upload[$i]['del_check'] = true;
        $row = sql_fetch(" select bf_file from {$g5['board_file_table']} where bo_table = '{$bo_table}' and wr_id = '{$iq_id}' and bf_no = '{$i}' ");
        @unlink(G5_DATA_PATH.'/file/'.$bo_table.'/'.$row['bf_file']);
        // 썸네일삭제
        if(preg_match("/\.({$config['cf_image_extension']})$/i", $row['bf_file'])) {
            delete_board_thumbnail($bo_table, $row['bf_file']);
        }
    }
    else
        $upload[$i]['del_check'] = false;
    $tmp_file  = $_FILES['bf_file']['tmp_name'][$i];
    $filesize  = $_FILES['bf_file']['size'][$i];
    $filename  = $_FILES['bf_file']['name'][$i];
    $filename  = get_safe_filename($filename);
    // 서버에 설정된 값보다 큰파일을 업로드 한다면
    if ($filename) {
        if ($_FILES['bf_file']['error'][$i] == 1) {
            $file_upload_msg .= '\"'.$filename.'\" 파일의 용량이 서버에 설정('.$upload_max_filesize.')된 값보다 크므로 업로드 할 수 없습니다.\\n';
            continue;
        }
        else if ($_FILES['bf_file']['error'][$i] != 0) {
            $file_upload_msg .= '\"'.$filename.'\" 파일이 정상적으로 업로드 되지 않았습니다.\\n';
            continue;
        }
    }
    if (is_uploaded_file($tmp_file)) {
        // 관리자가 아니면서 설정한 업로드 사이즈보다 크다면 건너뜀
        if (!$is_admin && $filesize > 22097152) {
            $file_upload_msg .= '\"'.$filename.'\" 파일의 용량('.number_format($filesize).' 바이트)이 게시판에 설정('.number_format(22097152).' 바이트)된 값보다 크므로 업로드 하지 않습니다.\\n';
            continue;
        }
        //=================================================================\
        // 090714
        // 이미지나 플래시 파일에 악성코드를 심어 업로드 하는 경우를 방지
        // 에러메세지는 출력하지 않는다.
        //-----------------------------------------------------------------
        $timg = @getimagesize($tmp_file);
        // image type
        if ( preg_match("/\.({$config['cf_image_extension']})$/i", $filename) ||
             preg_match("/\.({$config['cf_flash_extension']})$/i", $filename) ) {
            if ($timg['2'] < 1 || $timg['2'] > 16)
                continue;
        }
        //=================================================================
        $upload[$i]['image'] = $timg;
        // 4.00.11 - 글답변에서 파일 업로드시 원글의 파일이 삭제되는 오류를 수정
        if ($w == 'u') {
            // 존재하는 파일이 있다면 삭제합니다.
            $row = sql_fetch(" select bf_file from {$g5['board_file_table']} where bo_table = '$bo_table' and wr_id = '{$iq_id}' and bf_no = '$i' ");
            @unlink(G5_DATA_PATH.'/file/'.$bo_table.'/'.$row['bf_file']);
            // 이미지파일이면 썸네일삭제
            if(preg_match("/\.({$config['cf_image_extension']})$/i", $row['bf_file'])) {
                delete_board_thumbnail($bo_table, $row['bf_file']);
            }
        }
        // 프로그램 원래 파일명
        $upload[$i]['source'] = $filename;
        $upload[$i]['filesize'] = $filesize;
        // 아래의 문자열이 들어간 파일은 -x 를 붙여서 웹경로를 알더라도 실행을 하지 못하도록 함
        $filename = preg_replace("/\.(php|pht|phtm|htm|cgi|pl|exe|jsp|asp|inc)/i", "$0-x", $filename);
        shuffle($chars_array);
        $shuffle = implode('', $chars_array);
        // 첨부파일 첨부시 첨부파일명에 공백이 포함되어 있으면 일부 PC에서 보이지 않거나 다운로드 되지 않는 현상이 있습니다. (길상여의 님 090925)
        $upload[$i]['file'] = abs(ip2long($_SERVER['REMOTE_ADDR'])).'_'.substr($shuffle,0,8).'_'.replace_filename($filename);
        $dest_file = G5_DATA_PATH.'/file/'.$bo_table.'/'.$upload[$i]['file'];
        // 업로드가 안된다면 에러메세지 출력하고 죽어버립니다.
        $error_code = move_uploaded_file($tmp_file, $dest_file) or die($_FILES['bf_file']['error'][$i]);
        // 올라간 파일의 퍼미션을 변경합니다.
        chmod($dest_file, G5_FILE_PERMISSION);
    }
}
for ($i=0; $i<count($upload); $i++)
{
    if (!get_magic_quotes_gpc()) {
        $upload[$i]['source'] = addslashes($upload[$i]['source']);
    }
    $row = sql_fetch(" select count(*) as cnt from {$g5['board_file_table']} where bo_table = '{$bo_table}' and wr_id = '{$iq_id}' and bf_no = '{$i}' ");
    if ($row['cnt'])
    {
        // 삭제에 체크가 있거나 파일이 있다면 업데이트를 합니다.
        // 그렇지 않다면 내용만 업데이트 합니다.
        if ($upload[$i]['del_check'] || $upload[$i]['file'])
        {
            $sql = " update {$g5['board_file_table']}
                        set bf_source = '{$upload[$i]['source']}',
                             bf_file = '{$upload[$i]['file']}',
                             bf_content = '{$bf_content[$i]}',
                             bf_filesize = '{$upload[$i]['filesize']}',
                             bf_width = '{$upload[$i]['image']['0']}',
                             bf_height = '{$upload[$i]['image']['1']}',
                             bf_type = '{$upload[$i]['image']['2']}',
                             bf_datetime = '".G5_TIME_YMDHIS."'
                      where bo_table = '{$bo_table}'
                                and wr_id = '{$iq_id}'
                                and bf_no = '{$i}' ";
            sql_query($sql);
        }
        else
        {
            $sql = " update {$g5['board_file_table']}
                        set bf_content = '{$bf_content[$i]}'
                        where bo_table = '{$bo_table}'
                                  and wr_id = '{$iq_id}'
                                  and bf_no = '{$i}' ";
            sql_query($sql);
        }
    }
    else
    {
        $sql = " insert into {$g5['board_file_table']}
                    set bo_table = '{$bo_table}',
                         wr_id = '{$iq_id}',
                         bf_no = '{$i}',
                         bf_source = '{$upload[$i]['source']}',
                         bf_file = '{$upload[$i]['file']}',
                         bf_content = '{$bf_content[$i]}',
                         bf_download = 0,
                         bf_filesize = '{$upload[$i]['filesize']}',
                         bf_width = '{$upload[$i]['image']['0']}',
                         bf_height = '{$upload[$i]['image']['1']}',
                         bf_type = '{$upload[$i]['image']['2']}',
                         bf_datetime = '".G5_TIME_YMDHIS."' ";
        sql_query($sql);
    }
}
$row = sql_fetch(" select max(bf_no) as max_bf_no from {$g5['board_file_table']} where bo_table = '{$bo_table}' and wr_id = '{$iq_id}' ");
for ($i=(int)$row['max_bf_no']; $i>=0; $i--)
{
    $row2 = sql_fetch(" select bf_file from {$g5['board_file_table']} where bo_table = '{$bo_table}' and wr_id = '{$iq_id}' and bf_no = '{$i}' ");
    // 정보가 있다면 빠집니다.
    if ($row2['bf_file']) break;
    // 그렇지 않다면 정보를 삭제합니다.
    sql_query(" delete from {$g5['board_file_table']} where bo_table = '{$bo_table}' and wr_id = '{$iq_id}' and bf_no = '{$i}' ");
}
$row = sql_fetch(" select count(*) as cnt from {$g5['board_file_table']} where bo_table = '{$bo_table}' and wr_id = '{$iq_id}' ");
sql_query(" update {$g5['g5_shop_item_qa_table']} set qa_file = '{$row['cnt']}' where iq_id = '{$iq_id}' ");
// 자동저장된 레코드를 삭제한다.
sql_query(" delete from {$g5['autosave_table']} where as_uid = '{$uid}' ");

// *******************************
// ****** //2018-03-21 파일 *******
// *******************************
/*
if ($file_upload_msg) {
    alert($file_upload_msg, G5_SHOP_URL.'/itemqaform.php?it_id='.$it_id);
} else {
    if($w == 'd') {
        alert($alert_msg, $url);
    } else {
        alert_opener($alert_msg, $url);
    }
}
*/
?>
 

이 질문에 댓글 쓰기 :

답변 1

//등록시에 고유 아이디를 정의해 보세요
//66라인에 


if ($w == "")
{
    $sql = "insert {$g5['g5_shop_item_qa_table']}
               set it_id = '$it_id',
                   mb_id = '{$member['mb_id']}',
                   iq_secret = '$iq_secret',
                   iq_name  = '$iq_name',
                   iq_email = '$iq_email',
                   iq_hp = '$iq_hp',
                   iq_password  = '$iq_password',
                   iq_subject  = '$iq_subject',
                   iq_question = '$iq_question',
                   iq_time = '".G5_TIME_YMDHIS."',
                   iq_ip = '$REMOTE_ADDR',
                   device = '$device',
                   qa_option = 'html1'";
    sql_query($sql);
    $iq_id = sql_insert_id(); //<--- 이부분을 추가해 주세요    
    
    
    $alert_msg = '1:1문의가 등록 되었습니다.';
}
else if ($w == "u")
답변을 작성하시기 전에 로그인 해주세요.
전체 123,625 | RSS
QA 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT