How to add an insert to save the name of the images in my mysql database

1

I would like to obtain the name of each one of the images uploaded to the web server and save them in my database for later reference.  to see if someone gives me a hand.

Thanks for your help

Here I leave the script that I use to upload the images

foreach ($ _ FILES ['files'] ['name'] as $ i = > $ name) {

$name = $_FILES['files']['name'][$i];
$size = $_FILES['files']['size'][$i];
$type = $_FILES['files']['type'][$i];
$tmp = $_FILES['files']['tmp_name'][$i];

$explode = explode('.', $name);

$ext = end($explode);

$path = 'uploads/';
$path = $path . basename( $explode[0] . time() .'.'. $ext);

$errors = array();

if(empty($_FILES['files']['tmp_name'][$i])) {
    $errors[] = 'Please choose at least 1 file to be uploaded.';
}else {

    $allowed = array('jpg','jpeg','gif','bmp','png');

    $max_size = 4000000; // 4MB

    if(in_array($ext, $allowed) === false) {
        $errors[] = 'The file <b>'.$name.'</b> extension is not allowed.';
    }

    if($size > $max_size) {
        $errors[] = 'The file <b>'.$name.'</b> size is too hight.';
    }

}

if(empty($errors)) {

    if(!file_exists('uploads')) {
        mkdir('uploads', 0777);
    }

    if(move_uploaded_file($tmp, $path)) {
        echo '<p>The file <b>'.$name.'</b> successfully uploaded</p>';
    }else {
        echo 'Something went wrong while uploading the file <b>'.$name.'</b>';
    }

}else {
    foreach($errors as $error) {
        echo '<p>'.$error.'<p>';
    }
}

}

    
asked by Maicol Romero 14.10.2017 в 06:45
source

1 answer

1

Since you do not provide additional information on how to make the connection or the table in which you want to save the data, I will give you a generic example of how to insert into the database using pure php functions.

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

You can put this code in a function and call it when the upload of the file is successful. The name of the file is already in the variable that in your script is called $name

You left the reference in case you want to expand

Greetings.

    
answered by 08.11.2017 / 22:43
source