2017-11-03 11 views
0

코딩에 초보자입니다.PHP 함수를 사용하여 MySQL DB에서 HTML로 이미지 이름 검색하기

PHP 함수를 사용하여 MySQL 데이터베이스에서 이미지를 가져 오는 웹 사이트를 만들어야하지만 DB에 이미지를 저장할 수없고 이름 만 수동으로 넣을 수는 없습니다. getImage(1)

그래서 나는이 두 가지 기능이 있습니다

function getImage($imgid) { 
    $sql_command = "SELECT * FROM images WHERE id=$imgid;"; 
    $result = mysqli_query(getConnection(), $sql_command); 
    if($result) { 
     $result = mysqli_fetch_assoc($result); 
     return $result; 
    } else { 
     echo "Error <br /> " . mysqli_error(getConnection()); 
     return NULL; 
    } 
} 


function getImages() { 
    $sql_command = "SELECT * FROM images;"; 
    $result = mysqli_query(getConnection(), $sql_command); 
    if($result) { 
     return $result; 
    } else { 
     echo "Error."; 
     return NULL; 
    } 
} 

내가 다음에 파일을 포함 내 index.php하지만, 솔직히, 나는 실제로 이러한 기능을 적용하고 이미지의 이름을 지정하는 방법에 대한 이해 부족, 그것은 변수이기 때문입니다.

누군가가 나를 위해이 문제를 해결할 것이라고 기대하지 않습니다. 논리를 설명하거나 이와 같은 상황을 설명하는 유용한 리소스에 대한 링크를 공유하기 만하면됩니다.

+0

getImages ($ imgid = NULL) {} –

답변

0

일반적으로 이미지는 디렉토리에 있습니다. 그리고 이미지 이름이 데이터베이스에 저장됩니다. 당신은 모든 이미지의 이름을 받고 루프를 사용하여 표시

$sql = "SELECT * FROM images"; 
$imageresult1 = mysql_query($sql); 

    while($rows=mysql_fetch_assoc($imageresult1)) 
    { 
     $image = $rows['image']; 
     echo "<img src=/path/to/'$image' >"; 
     echo "<br>"; 
    } 
0

내가 당신이 원하는 정확히 이해한다면 모르겠지만, 데이터베이스에이 경로를 어디에 저장해야하는 쿼리를 만들 수 있습니다 그것은 서버 상에 저장 될 것이고, 그 다음 당신은 그들을 나열 할 수 있습니다.

<?php 
function getImages() { 
    $sql_command = "SELECT * FROM images;"; 
    $result = mysqli_query(getConnection(), $sql_command); 
    if($result) { 

     $imgs = []; 
     while($rows=mysql_fetch_assoc($result)) { 
      $imgs[] = $rows; 
     } 
     return $imgs; 
    } else { 
     echo "Error."; 
     return NULL; 
    } 
} 

// list imgs 
$imgs = getImages(); 
foreach($imgs as $img) { 
    echo "<img src'{$img['path']}' />"; 
} 
+0

내 웹 사이트의 여러 위치에 여러 이미지가 있습니다. 과 같은 이름을 사용하여 데이터베이스에서 검색해야합니다. " 올바른 이미지를 올바른 위치에 배치하는 방법이 무엇인지 이해하지 못하는 이유는 많기 때문입니다. –

0

바라건대 다음은 어떻게 당신이 이미 가지고있는 기능을 사용하는 아이디어를 제공하고, 약간의 작업으로, 아약스를 사용하여 getImage($id)의 사용을 구현할 수 있습니다. 아래의 코드는 단지 이미지 이름보다는 이미지를 열 것을 name 저장 fullpath에 가정 또한

+-------------+------------------+------+-----+---------+----------------+ 
| Field  | Type    | Null | Key | Default | Extra   | 
+-------------+------------------+------+-----+---------+----------------+ 
| id   | int(10) unsigned | NO | PRI | NULL | auto_increment | 
| name  | varchar(512)  | YES |  | NULL |    | 
+-------------+------------------+------+-----+---------+----------------+ 

(DB를 테이블이 유사한 구조를 갖는 가정) DB를 조회 의해 검색된 이미지 표시 그 자체.

<?php 

    function getConnection(){ 
     $dbhost = 'localhost'; 
     $dbuser = 'root'; 
     $dbpwd = 'xxx'; 
     $dbname = 'xxx'; 
     $db = new mysqli($dbhost, $dbuser, $dbpwd, $dbname); 

     return $db; 
    } 


    function getImages(){ 
     /* 
      query the database to return the ID and name of ALL images 

     */ 
     try{ 
      /* two named fields - these will be returned later */ 
      $sql='select `id`,`name` from `images`'; 

      /* Get the db conn object */ 
      $db=getConnection(); 

      /* throw exception if we are unable to bind to db */ 
      if(!$db or !is_object($db)) throw new Exception('Failed to bind to database'); 

      /* query the db */ 
      $res=$db->query($sql); 

      /* throw an exception if the query failed */ 
      if(!$res) throw new Exception('sql query failed'); 

      /* prepare results and iterate through recordset */ 
      $results=array(); 
      while($rs=$res->fetch_object()) $results[ $rs->id ]=$rs->name; 

      /* return the array of results */ 
      return $results; 

     }catch(Exception $e){ 
      echo $e->getMessage(); 
      return false; 
     } 
    } 


    function getImage($id=false){ 
     /* 
      Query the database to return single image based upon ID 
     */ 
     try{ 
      /* If the id is not specified or empty throw exception */ 
      if(!$id)throw new Exception('Image ID was not specified'); 

      /* sql statement to execute */ 
      $sql='select `name` from `images` where `id`=?'; 

      /* get db conn object */ 
      $db=getConnection(); 

      /* throw exception if we are unable to bind to db */ 
      if(!$db or !is_resource($db)) throw new Exception('Failed to bind to database'); 

      /* Create a "Prepared Statement" object - avoid SQL injection !! */ 
      $stmt=$db->prepare($sql); 

      /* If the statement failed, throw exception */ 
      if(!$stmt)throw new Exception('Failed to prepare sql query'); 

      /* Bind the supplied ID to the sql statement */ 
      $stmt->bind_param('i', $id); 

      /* Execute the query */ 
      $res=$stmt->execute(); 
      if($res){ 

       /* Prepare results */ 
       $stmt->store_result(); 
       $stmt->bind_result($name); 
       $stmt->fetch(); 

       /* return the name of the image */ 
       return $name; 

      } else { 
       throw new Exception('sql query failed'); 
      } 
     }catch(Exception $e){ 
      echo $e->getMessage(); 
      return false; 
     } 
    } 
?> 
<!doctype html> 
<html> 
    <head> 
     <meta charset='utf-8' /> 
     <title>Images</title> 
     <style> 
      #images{ 
       width:90%; 
       float:none; 
       display:block; 
       margin:1rem auto; 
      } 
      #images > img { 
       float:none; 
       margin:1rem; 
       padding:1rem; 
       border:1px dotted gray; 
      } 
     </style> 
     <script> 
      document.addEventListener('DOMContentLoaded', function(){ 
       var col=Array.prototype.slice.call(document.getElementById('images').querySelectorAll('img')); 
       col.forEach(function(img){ 
        img.onclick=function(e){ 
         alert('You could send an ajax request, using the ID:' + this.dataset.imgid + ' and then use PHP at the server side to process the ajax request and return the specific image using "getImage(id)"') 
        } 
       }); 
      }, false); 
     </script> 
    </head> 
    <body> 
     <div id='images'> 
     <?php 
      $images = getImages(); 
      if(!empty($images)){ 
       foreach($images as $id => $name){ 
        echo "<img data-imgid='$id' src='$name' title='This image is called $name and has db ID $id' />"; 
       } 
      } 
     ?> 
     </div> 
    </body> 
</html>