简体   繁体   中英

PHP upload image name

I want to write a php code that uploads a file name to a database. I want to be able to first just upload the file name. So later i can look up its name and bring up the file. This is what i have so far HTML code :

<html>
<form method="post" action="image_record.php" enctype="multipart/form-data">
<p>
Please Enter the Member Name.
</p>
<p>
Member or Affiliates Name:
</p>
<input type="text" name="nameMember"/>
<p>
Upload File
<input type="file" name="file"><br><br>
</p>
<p>
<input type="submit" name="submit" value="Submit" />
</p>
<br/>
</form>
</html>

<html>
<head>
</head>
<body>
<?php
$name = $_POST["nameMember"];
$con = mysql_connect("localhost","root","password");
if (!$con) {
die("can not connect: " . mysql_error());
}
mysql_select_db("snippets",$con);
if(isset($_POST['submit']))
{
    $file_name = $_FILES["file"]["name"];
    //echo $file_name
    $query="INSERT INTO value (file) VALUES ('".$file_name."')";
}
mysql_query($query,$con);
mysql_close($con);
?>
</body>
</head>
</html>

ok so it uploads the file to myphp admin, but not the file name. That is fine, but how do i call the file name from a php code?

Stop using mysql_ deprecated functions

Use PDO / mysqli functions instead

in image_record.php

if(isset($_POST['submit']))
{
    $file_name = $_FILES["file"]["name"];}
    //echo $file_name

    $query="insert into your_table_name (column_name) values('".$file_name."')";
    $res=mysql_query($sql,$query);
}

Firstly , I tested your code and it did insert the filename into my DB.

My file column was set to VARCHAR(255) .

Now, if you want to show the filename after it has been uploaded, use the following: (assuming that's what you're asking).

$result = mysql_query("SELECT * FROM value");
while($row = mysql_fetch_array($result))
{
echo '<p>'.$row['file'].' </p>';

}

The above code will show all the files in that row after you uploaded.

If you wish to limit it to only one, use LIMIT 1

For example:

$result = mysql_query("SELECT * FROM value LIMIT 1");
while($row = mysql_fetch_array($result))
{
echo '<p>'.$row['file'].' </p>';

}

If you want to show the first record only with a limit of one, use:

SELECT * FROM value ORDER BY file ASC LIMIT 1

If you want to show only the last record with a limit of one, use:

SELECT * FROM value ORDER BY file DESC LIMIT 1

If you don't want to limit the amount of records shown, then just remove LIMIT 1


However, if you wish to later retrieve the uploaded file, you won't be able to because you haven't actually uploaded the file.

You will need to use the move_uploaded_file() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM