【问题标题】:Retrieving image names from MySQL DB in HTML using PHP functions使用 PHP 函数从 HTML 中的 MySQL DB 中检索图像名称
【发布时间】:2018-04-16 01:03:20
【问题描述】:

我是编码新手。

我必须创建一个网站,使用 PHP 函数从 MySQL 数据库中检索图像,但我不能将图像存储在数据库中,只能存储它们的名称,也不能像 @987654321 那样手动输入 ID @等

所以我有这两个功能:

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 中,但老实说,我对如何实际应用这些函数并指定图像的名称缺乏了解,因为它是一个变量。

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

【问题讨论】:

  • 使用带有 NULL 的单个函数,例如 unction getImages($imgid = NULL) {}

标签: php mysql data-retrieval


【解决方案1】:

通常,图像将位于目录中。并且图像的名称将保存在数据库中。然后,您可以进行查询以接收所有图像名称并使用循环显示它们

$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>";
    } 

【讨论】:

    【解决方案2】:

    我不确定我是否完全理解你想要做什么,但是在数据库中你必须在服务器上保存将要保存的路径,然后你可以列出它们。

    <?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']}' />";
    }
    

    【讨论】:

    • 我网站的不同位置有多个图像。我需要使用它们的名称从我的数据库中检索它们,例如 " 我不明白的是如何把正确的图像在正确的位置,因为有很多。
    【解决方案3】:

    希望以下内容可以帮助您了解如何使用您已经拥有的功能,并通过一些工作,通过使用 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-05
      • 2013-09-29
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多