2015-02-02 1 views
2

저는 데이터베이스에서 학생 작품을 가져와야하는 학교 프로젝트를 수행하고 있습니다.mysql은 각 데이터가 새로운 행을 추가 할 때마다 데이터를 검색합니다.

내 홈페이지에는 쿼리에서 반환 된 데이터를 보유 할 수 있도록 사전 설정이 10 개 있습니다. 난 단지 10 데이터를 검색 할 필요가 있기 때문에 나는 그것을 미리 설정합니다.

HTML은 다음

<div class="viewport-computer col-lg-12 visible-lg no-padding "> 
    <div class="col-lg-2 img_thumb_holder no-padding"> 
     <img class="img_thumb"> 
     <h2 class="caption">Author<br />Description</h2> 
    </div> 
    <div class="col-lg-2 img_thumb_holder no-padding"> 
     <img class="img_thumb"> 
     <h2 class="caption">Author<br />Description</h2> 
    </div> 
    <div class="col-lg-2 img_thumb_holder no-padding"> 
     <img class="img_thumb"> 
     <h2 class="caption">Author<br />Description</h2> 
    </div> 
    <div class="col-lg-2 img_thumb_holder no-padding"> 
     <img class="img_thumb"> 
     <h2 class="caption">Author<br />Description</h2> 
    </div> 
    <div class="col-lg-2 img_thumb_holder no-padding"> 
     <img class="img_thumb"> 
     <h2 class="caption">Author<br />Description</h2> 
    </div> 
    <div class="col-lg-2 img_thumb_holder no-padding"> 
     <img class="img_thumb"> 
     <h2 class="caption">Author<br />Description</h2> 
    </div> 
    <div class="col-lg-2 img_thumb_holder no-padding"> 
     <img class="img_thumb"> 
     <h2 class="caption">Author<br />Description</h2> 
    </div> 
    <div class="col-lg-2 img_thumb_holder no-padding"> 
     <img class="img_thumb"> 
     <h2 class="caption">Author<br />Description</h2> 
    </div> 
    <div class="col-lg-2 img_thumb_holder no-padding"> 
     <img class="img_thumb"> 
     <h2 class="caption">Author<br />Description</h2> 
    </div> 
</div> 

는 나는 내가 루프 때문에 잘 작동하고 다시 10 개 데이터를 가져 오기 위해 내 PHP로 조회 할 수 jQuery를 사용하여 내 10 사업부에

jQuery를

/* Home Page Autoload featured thumbnails based on computer viewport/mobile viewport 
    ================================================== */  
    $.ajax({ 
      type: "POST", 
      dataType: "json", 
      url: "CMS/PHP/displayFeatThumbs.php", 
      success: function(data) { 
       // Display image thumbnail, caption & description of works onto each thumbnail div 
       $('.viewport-computer .img_thumb_holder img').each(function(index, element) { 
        // Work out the data to set 
        var imageUrl = "cms/" + data[index].links; 
        var captionHtml = "<span>" + data[index].caption + "<span class='spacer'></span><br/><span class='spacer'></span>" + data[index].title + "</span>" 
        // Now apply this to the elements 
        $(element).attr("src", imageUrl); // i must find a way to solve this 
        $(element).parent().css('background-image', 'url("'+imageUrl+'")'); 
        $(element).next().html(captionHtml); 

        // push the caption & id into global variable array to be used on other functions easily 
        captionArray.push(data[index].caption); 
        idArray.push(data[index].id); 
        homeLinksArray.push(data[index].links); 
        homeTitleArray.push(data[index].title); 
       }); 
     }); 

를 배치 내 미리 설정된 div (10 개)를 통해 다음 각 div에 데이터를 배치합니다. 이제 검색 막대 기능을 수행해야하며 모든 결과 (50 개 이상)를 반환합니다. 그들, 이제 문제는 내가 단지 사전 10divs, 그래서 내 흐름이

좋은 그래서 대신 아니라고 내 현재

loop through 10 div > retrieve data and place on 10 div 

내가 PHP와 아주 좋은 아닙니다에

retrieve all data, for each data, append a new div and place it 

싶습니다 저는 아직 새로운 학습자입니다. 그래서 어떻게 할 지에 대한 아이디어를 가지고 있지만, 저는 그것에 매달 렸습니다. 누군가가 각 데이터를 반복 할 수있는 방법을 알려주고 사전 설정 div 대신에 추가 할 수 있습니까?

PHP

<?php 
include 'dbAuthen.php'; 
$searchBar = $_POST['searchBar']; 
$sql = "SELECT userdatafiles.UserID,Name,Link,Title FROM userdatafiles JOIN users ON userdatafiles.UserID = users.UserID WHERE Skillsets = '$searchBar' GROUP BY UserID ORDER BY RAND()"; 

$result = mysqli_query($con,$sql); 
if (mysqli_num_rows($result) > 0) { 
    // output data of each row 
    while($row = mysqli_fetch_assoc($result)) { 
     echo '<div>hi</div>', 
     $links[] = array(
      "id" => $row["UserID"], 
      "links" => $row["Link"], 
      "caption" => $row["Name"], 
      "title" => $row["Title"], 
     );     
    } 
    //shuffle($links); 
    echo json_encode($links); 
} else { 
    echo "0 results"; 
} 
?> 

답변

0

솔루션은 50 명 div의 또는 UI에서 10 개 된 div를 미리 설정하지 않는 것입니다.

단순히 모든 레코드를 통해 결과 루프를 가져오고 div를 채우는 대신에 div를 즉석에서 만들고 데이터를 삽입하면됩니다. 새로 생성 된 div가 'new-data'와 같은 클래스 또는 UI에서 이러한 레코드가 다소 새로운 모습을 보여주기 위해 UI에 추가 할 준비가되었습니다. 데이터가 JSON은 PHP에 의해 반환 된 데이터가 여기에 모든 레코드의 모음입니다 나타냅니다 가정

은 당신이 정확한 JSON 응답을 보여 전까지 PHP에 의해 반환하여 JSON에 의존 할 수

for(i=0; i<data.length; i++) 
{ 
    $('<div class="col-lg-2 img_thumb_holder no-padding new-class">' 
     +'<img src="'+data[i].imgSrc+'" class="img_thumb">' 
     +'<h2 class="caption">'+data[i].author+'<br />'+data[i].description+'</h2>' 
     +'</div>').appendTo("ul#yourRecordHolderElemenet").slideDown("fast"); 
} 

정확한 솔루션을 하나의 방법입니다 우리는 당신을 제대로 도울 수 없을 것입니다.

전송되는 데이터의 양이 많아 질수록 PHP에서 HTML 마크 업과 함께 데이터를 반환하는 것을 권장하지 않습니다.여기 당신을 위해 완벽한 코드를 작성하지 않고

+0

감사 형제는, 내가 찾고 있어요 모두가 내가

+0

당신이 이미 1 & 2를 수행 오신 것을 환영합니다 :) –

0

는이

  1. 를 수행 select 쿼리 모든 레코드를 선택 mysqli 또는 pdo
  2. 와 데이터베이스 연결을 생성 할 수있는 방법을 단계별로 단계입니다 foreach 결과 집합
  3. foreach에 div을 추가하십시오.
  4. PHP wil L은 예를 들어, select 쿼리

에서 각 행 div을 추가

foreach($result->fetch_array() as $row) { 
    ?> 
    <div class="col-lg-2 img_thumb_holder no-padding"> 
     <img class="img_thumb"> 
     <h2 class="caption"><?= $row['author'] ?><br /><?= $row['description'] ?></h2> 
    </div> 
    <?php 
} 
+0

있습니다 , 그래서 내가 각각에 대해 새로운 매치 된 데이터 선택 권리를 발견 할 때마다 새로운 div를 추가하는 PHP에서 각각합니까? –

+0

당신이 맞습니다 – AgeDeO

+0

@jquerynerd HTML로 데이터를 추가하기 위해 ajax 요청을 사용할 필요가 없습니다. 데이터가 이미 데이터베이스에 있으므로 HTML에 직접 추가 할 수 있습니다. – Lepanto

0

PHP 코드 같아야

<?php 
include 'dbAuthen.php'; 
$searchBar = $_POST['searchBar']; 
$sql = "SELECT userdatafiles.UserID,Name,Link,Title FROM userdatafiles JOIN users ON userdatafiles.UserID = users.UserID WHERE Skillsets = '$searchBar' GROUP BY UserID ORDER BY RAND()"; 

$result = mysqli_query($con,$sql); 
if (mysqli_num_rows($result) > 0) { 
    // output data of each row 
    while($row = mysqli_fetch_assoc($result)) { 
     echo '<div>hi</div>', 
     $links = array(
      "id" => $row["UserID"], 
      "links" => $row["Link"], 
      "caption" => $row["Name"], 
      "title" => $row["Title"], 
     );     
    } 
    //shuffle($links); 
    echo json_encode(array('contents' => $links)); 
} else { 
    echo "0 results"; 
} 
?> 

통지 단일 차원 $link 어레이 json_encode에 연관 배열 . jQuery를에

, 당신의 success:이 /가 될 것입니다 수 있습니다

success: function(data){ 
    $.each(data.contents, function(ind, ele){ 
    // ele.id is the id and etc... or ind.id. :D 
    }); 
} 
+0

나는 추가에 대해 알고 있습니다. 단지 내가 데이터베이스에서 선택한 각 데이터를 반복하는 법을 모르겠습니다. 예를 들어 내 데이터베이스에서 사진을 검색하면 50 개의 결과가 반환되며이 50 개의 결과를 반복하고 50 개의 div를 추가 할 수 있습니다. 예, 나는 미리 정의하는 것이 나쁜 방법이라는 것을 알고 있습니다. 하하 –

+0

내 대답이 업데이트되었습니다. – Jigar

+0

감사합니다. 그것은 내가 뭘 찾고 –

0

이미 데이터베이스에있는 정보를 가지고 있기 때문에이 오히려 아약스 요청을보다 HTML에 직접 추가 할 수 있습니다.

<div class="viewport-computer col-lg-12 visible-lg no-padding "> 
<?php 
//You can get 10 records from database using 'limit 10' added to select query. 
//Get data from database. I assume you have the data in a variable $datafromdb 

foreach($datafromdb as $data){ 
?> 
    <div class="col-lg-2 img_thumb_holder no-padding"> 
     <img class="img_thumb"> 
     <h2 class="caption"><?=$data['author']?><br /><?=$data['description']?></h2> 
    </div> 
<?php } ?> 
</div> 
+0

어떻게 PHP는 HTML의 어느 부분에 div를 배치 알아? 나는 내가 PHP를 게시하여 어떻게 데이터를 검색하는지 보여줄 것이다. 업데이트 된 게시물 –

관련 문제