2012-12-17 5 views
0

안녕하세요, 내 이미지 업로드 스크립트 파일 디렉토리에 업로드시 date_added, user_id 및 ID뿐만 아니라 내 데이터베이스에 파일 이름을 삽입하려고합니다.이미지 업로드시 데이터베이스에 삽입 하시겠습니까?

현재 업로드하고 파일 디렉토리에 저장하지만 데이터베이스에 삽입 할 수 없습니다.

테이블 이름은 ptb_photos이고 열은 id, user_id (id = user_id), file_name 및 date_added입니다.

내 코드는 다음과 같습니다. 누군가 내가 잘못 가고있는 부분을 알려줄 수 있습니까? 나는 php에 익숙하지 만 사과가 완전히 잘못되면 여전히 사과합니다.

<?php 
session_start() 
?> 
<? 
$sql=mysql_query("INSERT INTO ptb_photos SET file_name ='".addslashes($filename)."' WHERE id=".$_SESSION['user_id']." AND user_id=".$_SESSION['user_id'].""); 

// LOG 
$log = '=== ' . @date('Y-m-d H:i:s') . ' ===============================' . "\n" 
     . 'FILES:' . print_r($_FILES, 1) . "\n" 
     . 'POST:' . print_r($_POST, 1) . "\n"; 
$fp = fopen('upload-log.txt', 'a'); 
fwrite($fp, $log); 
fclose($fp); 


// Result object 
$r = new stdClass(); 
// Result content type 
header('content-type: application/json'); 


// Maximum file size 
$maxsize = 10; //Mb 
// File size control 
if ($_FILES['xfile']['size'] > ($maxsize * 1048576)) { 
    $r->error = "Max file size: $maxsize Kb"; 
} 


// Uploading folder 
$folder = 'files/'; 
if (!is_dir($folder)) 
    mkdir($folder); 

// If specifics folder 
$folder .= $_POST['folder'] ? $_POST['folder'] . '/' : ''; 
if (!is_dir($folder)) 
    mkdir($folder); 

// PASS USER_ID HERE 
$folder2 = '../'. '../'. 'data/'. 'photos/'. $_SESSION['user_id'] . '/'; 
if (!is_dir($folder2)) 
    mkdir($folder2); 

// New directory with 'files/USER_SESSION_ID/' 
$folder = $newDir . $folder2; 


// If the file is an image 
if (preg_match('/image/i', $_FILES['xfile']['type'])) { 

    $filename = $_POST['value'] ? $_POST['value'] : 
      $folder . 'pic1.jpg'; 
} else { 

    $tld = split(',', $_FILES['xfile']['name']); 
    $tld = $tld[count($tld) - 1]; 
    $filename = $_POST['value'] ? $_POST['value'] : 
      $folder . sha1(@microtime() . '-' . $_FILES['xfile']['name']) . $tld; 
} 


// Supporting image file types 
$types = Array('image/png', 'image/gif', 'image/jpeg'); 
// File type control 
if (in_array($_FILES['xfile']['type'], $types)) { 
    // Create an unique file name  
    // Uploaded file source 
    $source = file_get_contents($_FILES["xfile"]["tmp_name"]); 
    // Image resize 
    imageresize($source, $filename, $_POST['width'], $_POST['height'], $_POST['crop'], $_POST['quality']); 
} else 
// If the file is not an image 
if (in_array($_FILES['xfile']['type'], $types)) 
    move_uploaded_file($_FILES["xfile"]["tmp_name"], $filename); 



// File path 
$path = str_replace('upload_image_1.php', '', $_SERVER['SCRIPT_NAME']); 

// Result data 
$r->filename = $filename; 
$r->path = $path; 
$r->img = '<img src="' . $path . $filename . '" alt="image" />'; 

// Return to JSON 
echo json_encode($r); 

// Image resize function with php + gd2 lib 
function imageresize($source, $destination, $width = 0, $height = 0, $crop = false, $quality = 80) { 
    $quality = $quality ? $quality : 80; 
    $image = imagecreatefromstring($source); 
    if ($image) { 
     // Get dimensions 
     $w = imagesx($image); 
     $h = imagesy($image); 
     if (($width && $w > $width) || ($height && $h > $height)) { 
      $ratio = $w/$h; 
      if (($ratio >= 1 || $height == 0) && $width && !$crop) { 
       $new_height = $width/$ratio; 
       $new_width = $width; 
      } elseif ($crop && $ratio <= ($width/$height)) { 
       $new_height = $width/$ratio; 
       $new_width = $width; 
      } else { 
       $new_width = $height * $ratio; 
       $new_height = $height; 
      } 
     } else { 
      $new_width = $w; 
      $new_height = $h; 
     } 
     $x_mid = $new_width * .5; //horizontal middle 
     $y_mid = $new_height * .5; //vertical middle 
     // Resample 
     error_log('height: ' . $new_height . ' - width: ' . $new_width); 
     $new = imagecreatetruecolor(round($new_width), round($new_height)); 
     imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $w, $h); 
     // Crop 
     if ($crop) { 
      $crop = imagecreatetruecolor($width ? $width : $new_width, $height ? $height : $new_height); 
      imagecopyresampled($crop, $new, 0, 0, ($x_mid - ($width * .5)), 0, $width, $height, $width, $height); 
      //($y_mid - ($height * .5)) 
     } 
     // Output 
     // Enable interlancing [for progressive JPEG] 
     imageinterlace($crop ? $crop : $new, true); 

     $dext = strtolower(pathinfo($destination, PATHINFO_EXTENSION)); 
     if ($dext == '') { 
      $dext = $ext; 
      $destination .= '.' . $ext; 
     } 
     switch ($dext) { 
      case 'jpeg': 
      case 'jpg': 
       imagejpeg($crop ? $crop : $new, $destination, $quality); 
       break; 
      case 'png': 
       $pngQuality = ($quality - 100)/11.111111; 
       $pngQuality = round(abs($pngQuality)); 
       imagepng($crop ? $crop : $new, $destination, $pngQuality); 
       break; 
      case 'gif': 
       imagegif($crop ? $crop : $new, $destination); 
       break; 
     } 
     @imagedestroy($image); 
     @imagedestroy($new); 
     @imagedestroy($crop); 


    } 
} 


?> 
+0

(1) 리틀 조언 : 사용 wideimage을 PHP에서 GD 이미지 조작을위한 라이브러리> http://wideimage.sourceforge.net/ (2) mysql_query (...) 또는 die (mysql_error());를 사용하여 오류보기 (3) mysqli 또는 pdo 사용 –

+0

** 결코'addslashes'를 사용하지 마십시오! 당신은 아직도 *'mysql_' 함수 군을 사용하고 있습니다. 즉, [mysql_real_escape_string'] (http://php.net/mysql_real_escape_string) 대신에 ([mysql_set_charset'] (http : //php.net/mysql_set_charset)). 또한 [PDO] (http://php.net/book.pdo)와 같이 더 이상 사용되지 않는 라이브러리를 조사해야합니다. – Charles

답변

0

이 시도 :

$sql = mysql_query('INSERT INTO ptb_photos (file_name, id, user_id) 
values ("$filename","$_SESSION[user_id]", "$_SESSION[user_id]"'); 

을 그건 그렇고, 구문 삽입 반 WHERE 절 가질 수 없어, 당신이 사용하지 않는 :

INSERT INTO ... SELECT * FROM ... WHERE 
관련 문제