0

I want to insert some data to database by query in PHP. I have something like this.

$zp='INSERT INTO `user`(`name`, `password`, `avatar`) VALUES ("'.$_POST['login'].'","'.$_POST['password'].'")';

And i want to put in the third value

<img src="$file_name.$file_type"/>

But I have no idea how to write this in PHP query

1 Answers1

0

You need to create an upload functionality, and to save only the path where you're images are stored.

Create a table in your database, with few column names: filepath, mime, size.

A little example: index.php:

if(isset($_FILES['file']['name'])){
    $name = $_FILES['file']['name'];
    $mime = $_FILES['file']['type'];
    $size = $_FILES['file']['size'];
    $tmp  = $_FILES['file']['tmp_name'];
    $path = 'uploads/' . $name; //maybe you should create the uploads/ folder before running the script

    if(move_uploaded_file($tmp, $path)){
        $db = new PDO('mysql:host=localhost;dbname=your_db_name','your_db_user','your_db_pass');
        $stmt = $db->prepare('INSERT INTO your_table_name_here SET filepath=?,mime=?,size=?');
        $stmt->execute([$path,$mime,$size]);
        echo 'File uploaded successfully!';
    }
}
?>
<form action="index.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" name="submit" value="Upload">
</form>

Then you can grab all the saved paths, and add them as src attrbuite for your images.

//index.php
$stmt = $db->prepare('SELECT filepath FROM your_table_name_here');
$stmt->execute();
while($row = $stmt->fetch()){?>
    <img src="<?php echo $row['filepath']; ?>" alt="image">
<?php }

But notice this is just a super simple script, for your learning purposes, and this code must not be used in production mode, as is not safe.

Dan Costinel
  • 1,716
  • 1
  • 15
  • 23