使用PHP函数从HTML中检索MySQL DB中的图像名称

时间:2017-11-03 10:21:31

标签: php mysql data-retrieval

我是编码的新手。

我必须创建一个网站,使用PHP函数从MySQL数据库中检索图像,但是我不能将图像存储在数据库中,只能存储它们的名称,而且我无法手动输入ID如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中,但老实说,我对如何实际应用这些功能并指定图像名称缺乏了解,因为它是一个变量。

我不希望有人为我解决这个问题,只是为了解释逻辑,或者分享一个有用资源的链接来解释这样的情况。

3 个答案:

答案 0 :(得分: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>";
    } 

答案 1 :(得分: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']}' />";
}

答案 2 :(得分:0)

希望以下内容可以说明如何使用您已有的函数,并通过一些工作,使用ajax实现getImage($id)的使用。下面的代码将显示通过查询db找到的图像(假设db表具有与此类似的结构)

+-------------+------------------+------+-----+---------+----------------+
| 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>