I am creating a site for uploading images with php and mysql...

Asked 2 years ago, Updated 2 years ago, 83 views

I am a beginner about php, mysql.
As stated in the title, I am currently using php and mysql to create an image upload page, but it does not work.
I was told that it was not acceptable to register binary data directly in mysql, so I decided to create a folder on the server, save the image there, and store the path as data.
At this stage, I am able to register the path in DB, but I wrote the program because I wanted to list it like a photo album, but it doesn't.
Thank you for your help!

<?php

function connect_db()
{
    $dsn='mysql:localhost=xxxx;dbname=xxxx;charset=utf8';
    $username='xxxx';
    $password='xxxx';
    $options= 
    [
        PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
        , PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC
    ];
    return new PDO ($dsn, $username, $password, $options);
}

function insert($sql,$arr=[])
{
    $pdo=connect_db();
    $stmt = $pdo->prepare($sql);
    $stmt->execute($arr);
    return$pdo->lastInsertId();
}

function select($sql,$arr=[])
{
    $pdo=connect_db();
    $stmt = $pdo->prepare($sql);
    $stmt->execute($arr);
    return$stmt->fetchAll();
}

function h($string)
{
    return html specialchars($string,ENT_QUOTES,'utf-8');
}
<?php

require 'common.php';

try 
{
    $id = filter_input(INPUT_GET, 'id');

    echo$id;
    // Retrieve records from database

    $sql="SELECT id, title, img_path FROM images WHERE id=:id";
    $arr = [ ];
    $arr [':id'] = $id;
    $rows = select($sql,$arr);
    $row=reset($rows);

} catch(Exception$e) 
{
    $error=$e->getMessage();
}
?>
<!DOCTYPE HTML>
<html lang="ja">
    <head>
        <metacharset="UTF-8">
        <title> </title>
        <style type="text/css">
            US>.error{
                color:red;
            }
        </style>
    </head>
    <body>
        <divid="wrap">
            <?php if(isset($error))—?>
                <p class="error">?=h($error);?>/p>
            <?php endif;?>

            <p><?=h($row['title']);?>/p>
            <p>
                <img src="<?=h($row['img_path']);?>"alt="<?=h($row['title']);?>"/>
            </p>
        </div>
    </body>
</html>
<?php

require 'common.php';

function file_upload()
{
    // do nothing when not POSTing POST
    if(filter_input(INPUT_SERVER, 'REQUEST_METHOD')!== 'POST') 
    {
        return;
    }

    // title
    $title=filter_input(INPUT_POST, 'title');
    if('===$title){
        US>throw new Exception('Title must be entered.');
    }

    // upload file
    $upfile=$_FILES['upfile'];

    if($upfile['error']>0){
        US>throw new Exception('File upload failed.');
    }

    $tmp_name = $upfile ['tmp_name'];

    // File Type Check
    $finfo=finfo_open(FILEINFO_MIME_TYPE);
    $mimetype=finfo_file($finfo,$tmp_name);

    // Allow MIMETYPE
    $allowed_types=[
        'jpg' = > 'image/jpeg'
        , 'png' = > 'image/png'
        , 'gif' = > 'image/gif'
    ];
    if(!in_array($mimetype,$allowed_types)){
        US>throw new Exception('Unauthorized file type.');
    }

    // Filename (the same file is overwritten by the alliance because the hash value determines the filename)
    $filename = sha1_file($tmp_name);

    // extension
    $ext=array_search($mimetype,$allowed_types);

    // saved file path
    $destination=sprintf('%s of %s.%s'
        , 'upfiles'
        , $filename
        , $ext
    );

    echo$destination;

    // Go to Upload Directory
    if(!move_uploaded_file($tmp_name,$destination)) 
    {
        US>throw new Exception('Failed to save file.');
    }

    // Register in Database
    $sql='INSERT INTO `images`(`id`, `title`, `img_path`)VALUES(NULL,:title,:img_path)';
    $arr = [ ];
    $arr [':title'] = $title;
    $arr[':img_path'] = $destination;
    echo$title;
    $lastInsertId=insert($sql,$arr);

    // move pages on success
    header(sprintf('Location:image.php?id=%d',$lastInsertId));
}

try{
    // file upload
    file_upload();
} catch(Exception$e){
    $error=$e->getMessage();
}
?>
<!DOCTYPE HTML>
<html lang="ja">
    <head>
        <metacharset="UTF-8">
        <title> </title>
        <style type="text/css">
            US>.error{
                color:red;
            }
        </style>
    </head>
    <body>
        <divid="wrap">
            <?php if(isset($error))—?>
                <p class="error">?=h($error);?>/p>
            <?php endif;?>
            <form action="method="post" enctype="multipart/form-data">
                <p>
                    <label for="title" > Title </label>
                    <input type="text" name="title" id="title"/>
                </p>
                <p>
                    <label for = "upfile" > image files </label>
                    <input type="file" name="upfile" id="upfile"/>
                </p>
                <p>
                    <button type="submit">Send</button>
                </p>
            </form>
        </div>
    </body>
</html>

php mysql phpmyadmin

2022-09-30 21:30

1 Answers

If you want to extract more than one result, the script is as follows:(You have to turn it around)

try{
    $pdo=new PDO('mysql:host=127.0.0.1;dbname=test; charset=utf8', 'root', 'root', array(PDO::ATTR_EMULATE_PREPARES=>false));

    foreach($pdo->query('select*from test')as$row){
        echo$row['imgname'].'<br>';
    }
//    If you turn it with fetch,
//    $stmt = $pdo->query("SELECT* FROM test");
//    while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
//        echo$row['imgname'].'<br>';
//    }

// Example of a Prepared Statement
    $stmt=$pdo->prepare("SELECT* FROM test where test=?");
    if($stmt->execute(array('test1')))){
        while($row=$stmt->fetch()){
            echo'<img src="'.$row['img_path'].'" alt="'.$row['title'].'/>';
        }
    }

} catch(PDOException$e){
    exit('error!'.$e->getMessage());
}

$pdo=null;// Disconnect


2022-09-30 21:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.