Получение имен изображений из БД MySQL в HTML с использованием функций PHP

Я новичок в кодировании.

Я должен создать веб-сайт, где изображения извлекаются из базы данных MySQL с использованием функций PHP, но я не могу хранить изображения в БД, только их имена, и я не могу вручную вставить идентификатор, как в getImage(1) и т.п.

Итак, у меня есть эти две функции:

function getImage($imgid) {
$sql_command = "SELECT * FROM images WHERE id=$imgid;";
$result = mysqli_query(getConnection(), $sql_command);
if($result) {
$result = mysqli_fetch_assoc($result);
return $result;
} else {
echo "Error <br /> " . mysqli_error(getConnection());
return NULL;
}
}function getImages() {
$sql_command = "SELECT * FROM images;";
$result = mysqli_query(getConnection(), $sql_command);
if($result) {
return $result;
} else {
echo "Error.";
return NULL;
}
}

Затем я включил файл в мой index.php но, честно говоря, мне не хватает понимания того, как на самом деле применять эти функции и указать имя изображения, так как это переменная.

Я не ожидаю, что кто-то решит эту проблему для меня, просто объяснит логику или, возможно, поделится ссылкой на полезный ресурс, который объяснит ситуацию, подобную этой.

0

Решение

Обычно изображение будет в каталоге. И название изображения будет сохранено в базе данных. Затем вы можете сделать запрос, чтобы получить все имена изображений и отобразить их с помощью цикла

$sql  = "SELECT * FROM images";
$imageresult1 = mysql_query($sql);

while($rows=mysql_fetch_assoc($imageresult1))
{
$image = $rows['image'];
echo "<img src=/path/to/'$image' >";
echo "<br>";
}
0

Другие решения

Я не уверен, что я точно понимаю, что вы хотите сделать, но в базе данных вам нужно сохранить путь, по которому он будет сохранен, представьте на сервере, затем вы можете перечислить их.

<?php
function getImages() {
$sql_command = "SELECT * FROM images;";
$result = mysqli_query(getConnection(), $sql_command);
if($result) {

$imgs = [];
while($rows=mysql_fetch_assoc($result)) {
$imgs[] = $rows;
}
return $imgs;
} else {
echo "Error.";
return NULL;
}
}

// list imgs
$imgs = getImages();
foreach($imgs as $img) {
echo "<img src'{$img['path']}' />";
}
0

Надеюсь, что следующее может дать представление о том, как использовать функции, которые у вас уже есть, и, немного поработав, реализовать использование getImage($id) используя ajax. Приведенный ниже код будет отображать изображения, найденные путем запроса к БД (при условии, что таблица БД имеет структуру, подобную этой)

+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| id          | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name        | varchar(512)     | YES  |     | NULL    |                |
+-------------+------------------+------+-----+---------+----------------+

А также при условии, что столбец name сохраняет полный путь к изображению, а не только само имя изображения.

<?php

function getConnection(){
$dbhost =   'localhost';
$dbuser =   'root';
$dbpwd  =   'xxx';
$dbname =   'xxx';
$db =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

return $db;
}function getImages(){
/*
query the database to return the ID and name of ALL images

*/
try{
/* two named fields - these will be returned later */
$sql='select `id`,`name` from `images`';

/* Get the db conn object */
$db=getConnection();

/* throw exception if we are unable to bind to db */
if( !$db or !is_object( $db ) ) throw new Exception('Failed to bind to database');

/* query the db */
$res=$db->query( $sql );

/* throw an exception if the query failed */
if( !$res ) throw new Exception('sql query failed');

/* prepare results and iterate through recordset */
$results=array();
while( $rs=$res->fetch_object() ) $results[ $rs->id ]=$rs->name;

/* return the array of results */
return $results;

}catch( Exception $e ){
echo $e->getMessage();
return false;
}
}function getImage( $id=false ){
/*
Query the database to return single image based upon ID
*/
try{
/* If the id is not specified or empty throw exception */
if( !$id )throw new Exception('Image ID was not specified');

/* sql statement to execute */
$sql='select `name` from `images` where `id`=?';

/* get db conn object */
$db=getConnection();

/* throw exception if we are unable to bind to db */
if( !$db or !is_resource( $db ) ) throw new Exception('Failed to bind to database');

/* Create a "Prepared Statement" object - avoid SQL injection !! */
$stmt=$db->prepare( $sql );

/* If the statement failed, throw exception */
if( !$stmt )throw new Exception('Failed to prepare sql query');

/* Bind the supplied ID to the sql statement */
$stmt->bind_param( 'i', $id );

/* Execute the query */
$res=$stmt->execute();
if( $res ){

/* Prepare results */
$stmt->store_result();
$stmt->bind_result( $name );
$stmt->fetch();

/* return the name of the image */
return $name;

} else {
throw new Exception('sql query failed');
}
}catch( Exception $e ){
echo $e->getMessage();
return false;
}
}
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>Images</title>
<style>
#images{
width:90%;
float:none;
display:block;
margin:1rem auto;
}
#images > img {
float:none;
margin:1rem;
padding:1rem;
border:1px dotted gray;
}
</style>
<script>
document.addEventListener( 'DOMContentLoaded', function(){
var col=Array.prototype.slice.call( document.getElementById('images').querySelectorAll('img') );
col.forEach(function(img){
img.onclick=function(e){
alert('You could send an ajax request, using the ID:' + this.dataset.imgid + ' and then use PHP at the server side to process the ajax request and return the specific image using "getImage(id)"')
}
});
}, false );
</script>
</head>
<body>
<div id='images'>
<?php
$images = getImages();
if( !empty( $images ) ){
foreach( $images as $id => $name ){
echo "<img data-imgid='$id' src='$name' title='This image is called $name and has db ID $id' />";
}
}
?>
</div>
</body>
</html>
0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector