2015-06-10 57 views
1

我有頁面向用戶顯示50個圖像,用戶可以點擊圖像並將該圖像加載到另一頁面。現在我想將每個圖像視圖保存到數據庫,即點擊圖像ID的計數器。 所以到目前爲止,我在表中添加了另一行,我稱之爲hits。在這裏,我展示圖片:如何在數據庫中保存頁面瀏覽量

$result = $pdo->prepare("SELECT * FROM images ORDER BY id ASC LIMIT $start_from, 50"); 
$result->execute(); 
for($i=0; $row = $result->fetch(); $i++) 
{ 
    echo '         
     <h1><a href="post.php?id='.$row['id'].'">'.$row['title'].'</a></h1> 
     <img src="../upload/'.$row['name'].'" alt=""/>'; 
} 

post.php這裏用戶只能看到這一形象,他點擊了我有這樣的:

if(isset($_GET['id']) && is_numeric($_GET['id'])) 
{ 
    $id = $_GET['id'];       
    $result = $pdo->prepare("SELECT * FROM images WHERE id= ?"); 
    if ($result->execute(array($_GET['id']))) 
    {    
     for($i=0; $row = $result->fetch(); $i++) 
     { 
      echo '  
       // source to show that image 
       '; 
     } 
    } 
} 

我明白我必須像這樣

更新 hits
UPDATE images SET hits = hits + 1 WHERE id = idofimage 

我不明白的是如何在當前代碼中實現更新。還在哪裏?

任何幫助表示讚賞。

回答

1

你幾乎擁有一切就迎刃而解了

只需添加更新代碼在同一個地方,你都顯示圖像

if(isset($_GET['id']) && is_numeric($_GET['id'])) 
{ 
    $id = $_GET['id'];       
    $result = $pdo->prepare("SELECT * FROM images WHERE id= ?"); 
    if ($result->execute(array($_GET['id']))) 
    {  
     //replace for by if because we are only getting one result 
     if($row = $result->fetch()) 
     { 
      //update the hits 
      $update = $pdo->prepare("UPDATE images SET hits = hits + 1 WHERE id = ?"); 
      //I prefer binding values and have a call to execute() 
      //but both options are ok 
      //$update->bindParam(1, $_GET['id'], PDO::PARAM_INT); 
      //$update->execute(); 
      $update->execute(array($_GET['id'])); 

      echo '  
       // source to show that image 
       '; 
     } 
    } 
} 
+0

感謝您的回答並更正了我的代碼。其實我真的不需要'for'和'array'。但是這不會更新數據庫中的命中。 – Select

+0

你有'=>'而不是'=',其中是UPDATE查詢。 ($ _get ['id']);'我已經出錯了,期待數組,但是給出了字符串,所以我再次執行它 - > execute(array($ _ GET ['id']) ))'。現在正在工作。 – Select

+0

更正了語法:) – PerroVerd

1

您必須先創建UPDATE語句,然後選擇SELECT才能顯示該單個圖像。應該是這樣的:

$result = $pdo->prepare("UPDATE images SET hits = hits + 1 WHERE id = ?"); 
$result->execute(array($_GET['id'])); 
$result = $pdo->prepare("SELECT * FROM images WHERE id= ?"); 
if ($result->execute(array($_GET['id']))) { 
    // .. rest of the code 

注意:不進行測試,我也還在學習PHP MySQL的&所以如果有更好的解決辦法,請大家指正。 謝謝。

+0

你的解決方案是爲我的幾乎是相同的,但我更喜歡後,我做了更新已檢查圖像是否存在 – PerroVerd

+0

是的,您的解決方案更好。我忘了檢查圖像是否真的存在。感謝您的評論和糾正我! –

相關問題