簡體   English   中英

使用 php 在 mysql 數據庫中插入隨機圖像

[英]Insert a random image in mysql database using php

我正在嘗試制作一個 CRUD 應用程序。 在創建頁面上,我必須有三個字段(標題、文本、類別)。 問題是我必須在 PHP 或 JS 中創建一個方法 / function 或 JS,從“圖像”文件中選擇隨機圖片並自動將其與其他 3 個字段一起加載到數據庫中。 然后它必須與其他 3 個字段一起出現在 admin.php 頁面上。

圖像具有幾乎相同的名稱,但最后一位不同 (1-2-3)

我不知道如何制作這個方法/功能。

我的 create.php 頁面

// Include config file
require_once "config.php";
 
// Define variables and initialize with empty values
$title = $text = $category =  "";
$title_err = $text_err = $category_err =  "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
 

    // Validate title
    $input_title = trim($_POST["title"]);
    if(empty($input_title)){
        $title_err = "Please enter a title.";
    } else{
        $title = $input_title;
    }
    
    // Validate text
    $input_text = trim($_POST["text"]);
    if(empty($input_text)){
        $text_err = "Please enter an text.";     
    } else{
        $text = $input_text;
    }
    
    // Validate category
    $input_category = trim($_POST["category"]);
    if(empty($input_category)){
        $category_err = "Please enter the category.";     
    } else{
        $category = $input_category;
    }

     // Check input errors before inserting in database
    if(empty($title_err) && empty($text_err) && empty($category_err)){
        // Prepare an insert statement
        $sql = "INSERT INTO informatii (title, text, category) VALUES (?, ?, ?)";
 
        if($stmt = $mysqli->prepare($sql)){
            // Bind variables to the prepared statement as parameters
            $stmt->bind_param("sss", $param_title, $param_text, $param_category, );
            
            // Set parameters
            $param_title = $title;
            $param_text = $text;
            $param_category = $category;
            
            // Attempt to execute the prepared statement
            if($stmt->execute()){
                // Records created successfully. Redirect to landing page
                header("location: admin.php");
                exit();
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
        }
     
    // Close statement
    $stmt->close();
}
}

?>
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Create Record</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
    .wrapper {
        width: 600px;
        margin: 0 auto;
    }
    </style>
</head>

<body>
    <div class="wrapper">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <h2 class="mt-5">Create Record</h2>
                    <p>Please fill this form and submit to add employee record to the database.</p>
                    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                        <div class="form-group">
                            <label>title</label>
                            <input type="text" name="title"
                                class="form-control <?php echo (!empty($title_err)) ? 'is-invalid' : ''; ?>"
                                value="<?php echo $title; ?>">
                            <span class="invalid-feedback"><?php echo $title_err;?></span>
                        </div>
                        <div class="form-group">
                            <label>Text</label>
                            <textarea name="text"
                                class="form-control <?php echo (!empty($text_err)) ? 'is-invalid' : ''; ?>"><?php echo $text; ?></textarea>
                            <span class="invalid-feedback"><?php echo $text_err;?></span>
                        </div>
                        <div class="form-group">
                            <label>Category</label>
                            <textarea name="category"
                                class="form-control <?php echo (!empty($category_err)) ? 'is-invalid' : ''; ?>"><?php echo $category; ?></textarea>
                            <span class="invalid-feedback"><?php echo $category_err;?></span>
                        </div>
                        <input type="submit" class="btn btn-primary" value="Submit">
                        <a href="index.php" class="btn btn-secondary ml-2">Cancel</a>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>

</html>

這應該讓您朝着正確的方向前進(保存圖像 src 就足夠了),您當然必須調整圖像文件夾的路徑和圖像名稱

$nr_images = 3;

$random_nr_index = random_int(1,$nr_images); 

$random_image_src = '/images/image-'.$random_nr_index.'.jpg'; 

要做到這一點,您需要不止一步創建:

  1. 一個簡單的 html 頁面發布 3 個字段值和圖像
  2. 一個 php 文件,接收 post 字段和圖像並保存到 mysql
  3. 一個簡單的 admin.PHP 頁面,顯示 3 個字段和圖像

如果您已經在服務器上有圖像,請在評論中指定它

步驟1:

<html>
<body>
<form method="POST" action="post.php">
f1:<input type="text" name="field1"><br>
f2:<input type="text" name="field2"><br>
f3:<input type="text" name="field3"><br>
im:<input type="file" name="image"><br>
<input type="submit" value="Save">
</form>
</body>
</html>

第 2 步:發布.php

<?php

$f1=$_POST["field1"];
$f2=$_POST["field2"];
$f3=$_POST["field3"];
$im=$_POST["image"];

if ($f1 == "" || $f2 == "" || $f3 == "" ){
    die("Errors: fields can't be empty! Go back check the fields and try Again");
} 

//Saving image on Server's file system if any image

if(isset($_POST["image"])) {

  //Saving image with no checking nothing: filetype, mime , extention (it may be very dangerous in a real server exposed to the public)

  $where_save = "images/";
  $im_name = basename($_FILES["image"]["name"]);
  $tmp_name = $_FILES["image"]["tmp_name"];
  move_uploaded_file ( $tmp_name , $where_save.$im_name );
  
}

$h  = "localhost";
$u  = "username";
$p  = "password";
$db = "yourDB";

// Creating connection to mysql server
$conn = mysqli_connect($h, $u, $p, $db);
// Checking connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

// WARNINGS ------------------------------------------------
// I do not care about security , please pay attention to it . 
// use some mysql_escape_string , or real_mysql_escape_string 
// could mitigate the violence of some sqlinjection attack

$sql = "INSERT INTO yourtable (field1, field2, field3,im_name)
VALUES ('$f1', '$f2', '$f3',$im_name)";

//executing mysql query to save data into it 
if (!mysqli_query($conn, $sql)) {

   die("Error: " . $sql . "<br>" . mysqli_error($conn));
} 
//closing connection  
mysqli_close($conn);

//Now we can redirect the user to admin.php  where we show data 
header("Location: admin.php");

?>

第 3 步:

<?php

$where_are_images="images/";

$h  = "localhost";
$u  = "username";
$p  = "password";
$db = "yourDB";

// Again creating connection to mysql server
$conn = mysqli_connect($h, $u, $p, $db);

if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

//now we want to read the data from mysql

$sql = "SELECT * FROM yourtable LIMIT 1"; //just limit to the first record
$result = mysqli_query($conn, $sql);
?>

<html>
<body>
<h2>Admin page</h2>
<em> hey every one can see top secret data here , Needs soma care about security!</em>

<?php while($d = mysqli_fetch_assoc($result)){  // LOOPING ?>
   
    <br>
    f1:<?= $d["field1"] ?><br>
    f2:<?= $d["field2"] ?><br>
    f3:<?= $d["field3"] ?><br>
    <img src="<?=$where_are_images.$d['im_name']?>">
    <br>
    <br>

<?php } ?>

</body>
</html>
<php? // CLOSING AND FREE RESOURCES
mysqli_free_result($result);
mysqli_close($conn); ?>

現在你有你需要的一切。 玩得開心用隨機圖像部分編輯它......我希望沒有錯誤(我沒有測試過)

暫無
暫無

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

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