簡體   English   中英

使列表中的元素可單擊(PHP)

[英]Make elements in a list clickable (PHP)

我目前正在開發一個簡單的網頁,使用戶能夠:將圖像和相應的標題上載到DB,讓用戶查看圖像並將其刪除。 我已經用以下代碼完成了前兩個:

<?php
#include_once("connection.php");
$db = new mysqli("192.168.2.2", "root", "", "proyectoti");
if ($db->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo "Información de servidor: ";
echo $db->host_info . "\n";

// Initialize message variable
  $msg = "";

  // If upload button is clicked ...
  if (isset($_POST['upload'])) {
    // Get image name
    $image = addslashes(file_get_contents($_FILES['image']['tmp_name']));  #$_FILES['image']['name'];
    // Get text
    $image_text = mysqli_real_escape_string($db, $_POST['image_text']);

    $sql = "INSERT INTO images (image, image_text) VALUES ('{$image}', '{$image_text}')";
    // execute query
    mysqli_query($db, $sql);
  }
  $result = mysqli_query($db, "SELECT * FROM images");

?>
<!DOCTYPE html>
<html>
<head>
<title>Proyecto TI | Sube imágenes</title>
<style type="text/css">
   #content{
    width: 50%;
    margin: 20px auto;
    border: 1px solid #cbcbcb;
   }
   form{
    width: 50%;
    margin: 20px auto;
   }
   form div{
    margin-top: 5px;
   }
   #img_div{
    width: 80%;
    padding: 5px;
    margin: 15px auto;
    border: 1px solid #cbcbcb;
   }
   #img_div:after{
    content: "";
    display: block;
    clear: both;
   }
   img{
    float: left;
    margin: 5px;
    width: 300px;
    height: 140px;
   }
</style>
</head>
<body>
<h1>Proyecto TI | <a> Interfaz </a></h1>
<div id="content">
  <?php
    while ($row = mysqli_fetch_array($result)) {
      echo "<div id='img_div'>";
        #echo "<img src='images/".$row['image']."' >";
        echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
        echo "<p>".$row['image_text']."</p>";
      echo "</div>";
    }
  ?>
  <form method="POST" action="index.php" enctype="multipart/form-data">
    <input type="hidden" name="size" value="1000000">
    <div>
      <input type="file" name="image">
    </div>
    <div>
      <textarea 
        id="text" 
        cols="40" 
        rows="4" 
        name="image_text" 
        placeholder="Di algo de esta imagen ^^"></textarea>
    </div>
    <div>
        <button type="submit" name="upload">Publicar</button>
    </div>
  </form>
</div>
</body>
</html>

看起來像這樣: 看起來如何

現在,我唯一缺少的就是能夠刪除圖像(基本上我只回顯每個圖像),您如何建議我完成此操作,使每個項目都可單擊,並彈出一個對話框或按鈕執行操作(從數據庫中刪除)。

我真的對PHP或CSS / HTML不太了解,將不勝感激,謝謝!

打開對話並在刪除項目之前詢問用戶,將要求您轉到另一個頁面進行刪除或為此使用JavaScript。 在這兩種情況下,您都應該以某種方式在html代碼中設置圖像的標識符。 我建議您給每個圖像一個id '<img ... id="'.$yourImageId.'">'或一個數據屬性'<img ... data-identifier="'.$yourImageId.'" >'和該標識符。

第一個變體:

...
echo '<a href="/path/to/delete/view/page.php?image=yourImageId">'
echo '<img ... id="'.$yourImageId.'"/>'
echo '</a>'
...

在這個delete-view-page上,您只有一個表單會觸發您的刪除代碼

<form action="/path/to/delete/view/page.php" method="POST">
<input type="hidden" name="id" value="<?php echo $yourImageId ?>">
</form>
<!-- after this, react with $_POST['id'] --> to the id sent to the server side and delete the image in your database -->

另一種方法不是服務器端渲染。 您應該給您的Elements一些類,例如“ my-clickable-image”。之后,您的頁面上會有一個腳本,如下所示:

<script>
/* get your images with querySelectorAll, the . stands for class and after that your name */
var clickables = document.querySelectorAll(".my-clickable-image");
clickables.foreach(function(image){
// say that for each image, when clicked the generated function is called   image.addEventListener('click',generateShowDialogueFunc(image.getAttr("id")));
});

// generate a function(!) that reacts to an image being clicked
function generateShowDialogueFunc(imageIdentifier){
 // return a function that adds a Pop Up to the page
 // the Pop Up has approximately the code of the first options second page
 // except that now, it must create and remove elements in javascript
 return function createPopUp(){
  removePopUp();
  var popup = document.createElement("div");
  popup.setAttribute("id","deletePopUp");
  var deleteForm = document.createElement("form");
  deleteForm.setAttr("action","/path/to/file/that/deletes/given/query.php?id="+imageIdentifier);
  var deleteContents = '<p> Do you want to delete this image? </p>'
  + '<button type="submit"> yes </button>'
  + '<button onclick="removePopUp()"> no </button>'
  deleteForm.innerHTML = deleteContents;
  document.body.appendChild()
 }
}

// remove the Pop Up that can be used to delete an image from the page
function removePopUp(){
 var existingPopUp = document.getElementById("deletePopUp");
 if(existingPopUp) document.body.removeChild(existingPopUp);
}
</script>

<!-- just add some styling to make the popup show on top of the page -->
<style>
  #deletePopUp{
    width: 50vw;
    height: 50vh;
    position: absolute;
    z-index: 1;
    padding: 1em;
  }
</style>

在這種情況下,您只需要調用服務器來刪除圖像,而不顯示刪除表單。


我建議第二個,但是對於基於意見的答案,不會進行堆棧溢出。

關於簡單的安全性:您的用戶似乎可以為圖像提供標題或文本。 嘗試如果用戶給出諸如<bold>some title</title>之類的標題會發生什么,並猜測如果標題為<script>window.location.href="google.com"</script> (XSS *提示)會發生什么提示*)

關於代碼結構:如果您想更頻繁地進行類似Web開發的工作,請考慮將數據庫訪問代碼和邏輯代碼與php頁面模板代碼分開,這被稱為3層體系結構,是大型項目的標准,但是我想這是實際上只是一個簡短的原型或測試。

在此循環中:

  <?php
    while ($row = mysqli_fetch_array($result)) {
      echo "<div id='img_div'>";
        #echo "<img src='images/".$row['image']."' >";
        echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
        echo "<p>".$row['image_text']."</p>";
      echo "</div>";
    }
  ?>

個人將添加一個具有唯一數據屬性的元素(例如“ x”或類似符號): https : //www.abeautifulsite.net/working-with-html5-data-attributes

您顯然必須添加圖像的唯一ID,因此您可以讓SQL知道要刪除的行...像這樣:

 echo "<div class='delete-image' data-id='" . $row['id'] . "'>x</div>';

然后,我將該類鏈接到AJAX調用,以向服務器發出異步請求並刪除圖像,而無需重新加載頁面。 這不是很難。

一個更簡單的解決方案是在循環中創建一個新表單,因此您可以為每個圖像創建多個表單, 表單中添加一個具有圖像ID的隱藏字段,並使用valeu“刪除”或簡單地“ x”創建一個提交按鈕。

創建支票的方式相同:

if (isset($_POST['upload'])) { ... }

您可以創建如下內容:

if (isset($_POST['delete-image'])) { ... }

您將像常規格式輸入一樣攜帶圖像id值。 您可以用它做任何您想做的事情。

我強烈建議您研究一下如何使用jquery和ajax調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM