简体   繁体   中英

Insert a random image in mysql database using php

I am trying to make a CRUD application. on the Create page I have to have three fields (title, text, category). the problem is that I have to make a method / function in PHP or JS that chooses a random picture from the "images" file and automatically loads it in the database along with the other 3 fields. then it has to appear on the admin.php page together with the other 3 fields.

Images have almost the same name except the last digit which differs (1-2-3)

I have no idea how to make this method/function.

my create.php page

// 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>

this should get you in the right direction (saving the image src is enough), you of course will have to adapt the path to your image folder, and image name

$nr_images = 3;

$random_nr_index = random_int(1,$nr_images); 

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

To do it you need more than one step creating:

  1. A simple html page to post 3 fields value and the image
  2. A php file that receive the post fields and the image and save into mysql
  3. A simple admin.PHP page that shows 3 fields and image

if you already have the images on the server please specify it in a comment

STEP 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>

STEP 2: post.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");

?>

STEP 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); ?>

Now you have all you need. Have fun editing it with random images part... I hope there are no error (i have not tested it)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM