No puedo insertar varias imágenes en la base de datos. Cuando estoy insertando las imágenes, solo se inserta una imagen. no todos insertados. He mostrado aquí el formulario con el código de inserción php. No he encontrado dónde está el problema. Por favor ayuda.
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove image</span>" +
"</span>").insertAfter("#files");
$(".remove").click(function(){
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
input[type="file"] {display: block;}
.imageThumb {max-height: 75px; border: 2px solid; padding: 1px; cursor: pointer;}
.pip {display: inline-block; margin: 10px 10px 0 0;}
.remove { display: block;background: #444;border: 1px solid black;color: white;text-align: center;cursor: pointer;}
.remove:hover {background: white;color: black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>Upload your images</h3>
<input type="file" id="files" name="files[]" multiple /><br>
<input type="submit" name="submit" value="Submit">
</div>
Este es el código php:
<?php
if(isset($_POST['submit']))
{
if(isset($_FILES['files']))
{
$n_arrays = $_FILES['files']['name'];
$tmp_name_arrays = $_FILES['files']['tmp_name'];
$type_arrays = $_FILES['files']['type'];
$size_arrays = $_FILES['files']['size'];
foreach ($tmp_name_arrays as $index => $val)
{
$n_array = $n_arrays[$index];
$tmp_name_array = $tmp_name_arrays[$index];
$type_array = $type_arrays[$index];
$size_array = $size_arrays[$index];
if(move_uploaded_file($tmp_name_array, "ad/data/img/".$n_array))
{
$sql = 'INSERT INTO `image`
SET `img_name` = ?, `img_type` = ?, `img_size` = ?';
// Prepare the SQL statement for execution.
$statement = $connection->prepare($sql);
$bound = $statement->bind_param('sss', $n_array, $type_array, $size_array);
// Execute the prepared statement.
$executed2 = $statement->execute();
if(!$executed2){
echo "error". mysqli_error($connection);
} else {
$_SESSION['s']="Images successfully saved";
header('location:posting_ad_image.php');
}
}
}
}
}
?>
Solo puedo cargar la última imagen que se cargó en último lugar. Todas las imágenes no se insertan en la base de datos phpmyadmin.
Como ya se señaló, su bucle se activó redirect
en la primera iteración y luego lo envió antes de que todas las imágenes pudieran guardarse y registrarse. El uso de prepared statements
se puede hacer de tal manera que realice la preparación y el enlace de las variables solo una vez, pero ejecute muchas veces hasta que se cierre la instrucción.
<?php
if( isset( $_POST['submit'],$_FILES['files'] ) ) {
$uploaded=array();
$n_arrays = $_FILES['files']['name'];
$tmp_name_arrays = $_FILES['files']['tmp_name'];
$type_arrays = $_FILES['files']['type'];
$size_arrays = $_FILES['files']['size'];
/* prepare the sql statement before the loop */
$sql = 'INSERT INTO `image` SET `img_name` = ?, `img_type` = ?, `img_size` = ?';
$statement = $connection->prepare( $sql );
if( $statement ){
/* if the statement was prepared successfully, bind the variables that will be used later */
$statement->bind_param('sss', $n_array, $type_array, $size_array );
/* iterate through the images, store the image and log to db */
foreach( $tmp_name_arrays as $index => $val ){
$n_array = $n_arrays[ $index ];
$tmp_name_array = $tmp_name_arrays[ $index ];
$type_array = $type_arrays[ $index ];
$size_array = $size_arrays[ $index ];
if( is_uploaded_file( $tmp_name_array ) ){
$bytes = move_uploaded_file( $tmp_name_array, "ad/data/img/".$n_array );
if( $bytes ){
$status = $statement->execute();
$uploaded[]=$status && $bytes ? $n_array : false;
}
}
}
/* close the statement and db connection */
$statement->close();
$connection->close();
/* remove empty entries from array - if any */
$uploaded=array_filter( $uploaded );
if( !empty( $uploaded ) ){
$_SESSION['s']=sprintf("%d Images successfully saved", count( $uploaded )-1 );
header('Location: posting_ad_image.php');
}
}
}
?>
Ok - Lo siguiente se hizo como una prueba completa de un extremo a otro y funciona bien ~ necesitará editar la $dir
variable para que se adapte
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$connection = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$dir='c:/temp/fileuploads/1/';
if( isset( $_POST['submit'], $_FILES['files'] ) ) {
$uploaded=array();
$sql = 'insert into `image` set `img_name` = ?, `img_type` = ?, `img_size` = ?';
$stmt = $connection->prepare( $sql );
if( $stmt ){
$stmt->bind_param( 'sss', $name, $type, $size );
foreach( $_FILES['files']['name'] as $i => $name ) {
if( !empty( $_FILES['files']['tmp_name'][$i] ) ) {
$name = $_FILES['files']['name'][$i];
$size = $_FILES['files']['size'][$i];
$type = $_FILES['files']['type'][$i];
$tmp = $_FILES['files']['tmp_name'][$i];
if( is_uploaded_file( $tmp ) ){
$bytes = move_uploaded_file( $tmp, $dir.$name );
if( $bytes ){
$status = $stmt->execute();
$uploaded[]=$status && $bytes ? $name : false;
}
}
}
}
if( !empty( $uploaded ) ){
$_SESSION['s']=sprintf("%d Images successfully saved", count( $uploaded )-1 );
header('Location: posting_ad_image.php');
}
}
}
?>
<!doctype html>
<html>
<head><title>Multiple file upload</title></head>
<body>
<form method='post' enctype='multipart/form-data'>
<input type='file' name='files[]' multiple />
<input type='submit' name='submit' value='Upload & save' />
</form>
</body>
</html>
Fragmento de db después de ejecutar y cargar algunas imágenes a la vez
mysql> describe image;
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| img_name | longblob | YES | | NULL | |
| img_type | varchar(50) | YES | | NULL | |
| img_size | int(11) | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
mysql> select * from image;
+-------------------------------------+------------+----------+
| img_name | img_type | img_size |
+-------------------------------------+------------+----------+
| tumblr_ook8swcsSt1tp499co1_1280.jpg | image/jpeg | 81124 |
| tumblr_ook8ukfiTY1tp499co1_1280.jpg | image/jpeg | 201061 |
| tumblr_ook8veeLgq1tp499co1_1280.jpg | image/jpeg | 63477 |
| tumblr_oomaozErOP1tp499co1_1280.jpg | image/jpeg | 283062 |
| tumblr_oomapxb8NJ1tp499co1_1280.jpg | image/jpeg | 577475 |
| tumblr_oomaqzKzlw1tp499co1_1280.jpg | image/jpeg | 382917 |
+-------------------------------------+------------+----------+
Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.
En caso de infracción, por favor [email protected] Eliminar
Déjame decir algunas palabras