sql >> Base de Datos >  >> RDS >> Mysql

Wordpress:obtener imágenes de db almacenadas como datos blob

Estás recibiendo todo información en la tabla para esa identificación de producto y luego intentar mostrarla como una imagen. Debe acceder a la imagen desde la matriz de resultados o SELECT solo la imagen, p. usa get_var en lugar de get_results y selecciona img en lugar de * :

$product_id = get_query_var('id');
$image = $wpdb->get_var("SELECT img FROM products  WHERE id = ".$product_id);

Por cierto, esto lo deja abierto a la inyección de SQL, por lo que realmente debería usar $wpdb->prepare para incluir una variable en su consulta, por ejemplo,

$image = $wpdb->get_var( 
    $wpdb->prepare("SELECT img FROM products  WHERE id = %d", $product_id)  
);

Limitación de tamaño de BLOB

Tenga en cuenta que un BLOB en MYSQL está limitado a 64kb. Si sus imágenes son más grandes que esto, necesitará usar un MEDIUMBLOB que es de 16 MB

Guarde la ruta de la imagen en lugar de directamente en la base de datos como un BLOB

Una solución más práctica es guardar solo el camino.

Para hacer esto, deberá crear una carpeta para cargar las imágenes (por ejemplo, en mi código a continuación, está en la raíz web y se llama myimages ), y una nueva columna VARCHAR o TEXT en su base de datos (se llama img_path en el ejemplo a continuación).

/* 1. Define the path to the folder where you will upload the images to, 
      Note, this is relative to your web root. */ 
define (MY_UPLOAD_DIR, "myimages/");

$imagefilename = basename( $_FILES['image']['name']);

/* 2. define the full path to upload the file to, including the file name */
$fulluploadpath = get_home_path(). MY_UPLOAD_DIR . $imagefilename;

$image_name = strip_tags($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);

/* 3. Do your validation checks here, e.g. */
if($image_size == FALSE) {
    echo 'The image was not uploaded';
} 
/* 4. if everything is ok, copy the temp file to your upload folder */
else if(move_uploaded_file($_FILES['image']['tmp_name'], $fulluploadpath )) {
    /* 5. if the file was moved successfully, update the database */
    $wpdb->insert( 
        $table, 
        array( 
            'title' => $title,
            'description' => $description,
            'brand' => $brand,
            'img_name' => $image_name,
            'img_path' => MY_UPLOAD_DIR . $imagefilename, /* save the path instead of the image */
        )
    ); 

} else {
    //Display an error if the upload failed
    echo "Sorry, there was a problem uploading your file.";
}

Para recuperar la imagen de la base de datos y mostrarla:

$product_id = get_query_var('id');
/* query the database for the image path */
$imagepath = $wpdb->get_var( 
    $wpdb->prepare("SELECT img_path FROM products  WHERE id = %d", $product_id)  
);

/* 6. Display the image using the path. 
      Because the path we used is relative to the web root, we can use it directly 
      by prefixing it with `/` so it starts at the webroot */ 
if ($imagepath)
    echo '<img src="/'.$imagepath.'" />';

El código anterior no se ha probado, pero la idea básica está ahí. Además, no funcionará si ya existe un archivo con el mismo nombre, por lo que es posible que desee considerar agregar una marca de tiempo al nombre para que sea único.

Referencia :