2013-10-22 2 views
0

일부 이미지가 표시되는 페이지가 있습니다 (데이터베이스 기반). 다음은 내 gallery.php 코드입니다.이미지를 업로드하고 데이터베이스 경로를 저장하는 방법은 무엇입니까?

<ul id="portfolio-list" class="gallery"> 
    <?php 
     $sql="select * from eikones "; 
     $res=mysql_query($sql); 
     $count=mysql_num_rows($res); 

     for ($i = 0; $i < $count; ++$i) 
     { 
      $row = mysql_fetch_array($res); 
      $co=$i+1; 
      if(isset($row[ "path" ])) 
      { 
       $path= $row[ "path" ]; 
      } 

      if(isset($row[ "auxon" ])) 
      { 
       $auxon = $row[ "auxon" ]; 
      } 


      if($_SESSION['role'] == "admin") 
       echo "<li class=\"pink\"><a href=\"$path\" rel=\"group1\" class=\"fancybox\" title=\"Προιόν \"><img src=\"$path\" alt=\"Pic\"></a></li>\n"; 

     } 

     ?> 


</ul> 

이제 이미지를 업로드 할 수있는 양식을 만들고 싶습니다. 나는 이것을 시도하고 있지만 작동하지 않습니다

<form enctype="multipart/form-data" action="gallery.php" method="post" name="changer"> 
<input name="image" accept="image/jpeg" type="file"> 
<input value="Submit" type="submit"> 
</form> 

<?php 

include 'conf.php'; //database connect 

if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) { 


    $tmpName = $_FILES['image']['tmp_name']; 


    $fp  = fopen($tmpName, 'r'); 
    $data = fread($fp, filesize($tmpName)); 
    $data = addslashes($data); 
    fclose($fp); 


    $query = "INSERT INTO eikones"; //table name = "eikones" and it has two columns named "auxon" and "path". The auxon is the id. 
    $query .= "(image) VALUES ('','$data')"; 
    $results = mysql_query($query, $link) or die(mysql_error()); 

    print "DONE"; 

    } 
    else { 
    print "NO IMAGE SELECTED"; 
    } 

?> 

그것은 "이미지가 선택되지"새로운 아무것도 데이터베이스에 온다 말한다.

+0

에만 넣어 하나 개의 열을 지정하는 경우, 두 값을 삽입 할 말있어 –

+0

에 @scrowler 도움이 되겠습니까? $ insert = mysql_query ("INSERT INTO eikones VALUES ('', '$ data')") 대신 2 줄을 사용합니까? –

답변

2

몇 시간 후에 해결책을 찾았습니다. 그것은 작동합니다. 비록 내가 여전히 두 번째 해결책을 찾게되어 기쁠 지 모르지만 (내가 처음 여기에 올린 코드에 따르면).

양식 페이지 :

<form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer"> 
<input name="image" accept="image/jpeg" type="file"> 
<input value="Submit" type="submit"> 
</form> 

삽입 데이터베이스 페이지 : 여기에 두 번째 솔루션입니다 첫째

<?php 

    include 'conf.php'; 

    if ($_FILES["image"]["error"] > 0) 
    { 
    echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />"; 
    echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED"; 
    } 
    else 
    { 
    move_uploaded_file($_FILES["image"]["tmp_name"],"images/" . $_FILES["image"]["name"]); 
    echo"<font size = '5'><font color=\"#0CF44A\">SAVED<br>"; 

    $file="images/".$_FILES["image"]["name"]; 
    $sql="INSERT INTO eikones (auxon, path) VALUES ('','$file')"; 

    if (!mysql_query($sql)) 
    { 
     die('Error: ' . mysql_error()); 
    } 
    echo "<font size = '5'><font color=\"#0CF44A\">SAVED TO DATABASE"; 

    } 

    mysql_close(); 

?> 
0

이미지 업로드를 처리하기 위해 다운로드 할 수있는 소규모 수업이 많이 있습니다. 여기 제가 작아 진 작은 것이 있습니다. 파일 형식 및 파일 크기에 대한 유효성을 설정할 수 있습니다. 만약 당신이 항상 같을 것이라면, 생성자에서 보호 된 변수를 private 또는 hardcode로 만드는 방법을 자유롭게 할 수 있습니다. 약간의 작업이 필요할 수도 있지만이 클래스를 사용하거나 절차 적으로 필요한 비트를 추출 할 수 있습니다. 사소한 실수는 용서하십시오.

class ImageUploader{ 

    protected 
     $size_limit, 
     $allowed_extensions; 
     $failed_saves; 

    public function __construct(int $limit, array $extensions){ 
     $this->size_limit = $limit; 
     $allowed_extensions = $extensions; 
    } 

    public function saveImage(array $images){ 
     foreach($images as $image){ 
      if($this->meetsSizeLimit($image['size'])){ 
       if($this->hasValidExtension(end(explode(".", $image["name"])))){ 
        $this->storeImage($image, $this->getNextImageIndex()); 
       } 
       else $failed_saves[$image["name"] = "Invalid file type."; 
      } 
      else $failed_saves["name"] = "File is too large."; 
     } 
     return $failed_saves; 
    } 

    public function meetsSizeLimit(int $size){ 
     return $size <= $this->size_limit; 
    } 

    public function hasValidExtension(string $extention){ 
     return in_array($extension, $this->allowed_extensions) 
    } 

    public function storeImage($image, $unique_id){ 
     move_uploaded_file($image["tmp_name"], "you_relative_file_path" . $image["name"]); 
     rename('your_relative_file_path' . $image["name"], 'your_relative_file_path/img' . $unique_id . '.' . $extension); 
     //Place your query for storing the image id and path in table 'eikones' 
    } 

    public function getNextImageIndex(){ 
     //Code to get the next available image id or MAX(id) from table 'eikones' 
    } 
} 
+0

지금 수업을 사용해도 상관 없어요. 그것은 간단한 관리 패널이고 내가 코드에서 잘못하고있는 것을 모른다. –

+0

출력이 "NO IMAGE SELECTED"이면, if (isset ($ _ FILES [ 'image']) && $ _FILES [ 'image'] [ 'size']> 0)'를 지나치지 않을 것입니다. 두 개의 if 문으로 나누고 둘 중 하나를 지나치는지 확인하는 것이 좋습니다. 또는 브라우저가 보내는 것을보기 위해'var_dump [$ _ FILES]'할 수 있습니다. – jpodwys

+0

나는 그들을 분리했고 아무 것도 효과가 없었다. 그렇게 쉬운가요? 파일 경로를 가져 와서 변수에 넣는 방법이 있다고 가정합니다. 예 : $ path = (그렇게하는 함수). 그리고이 $ 경로를 표에 삽입합니다. –

관련 문제