我正在使用php开发一个个人使用的应用程序。我想要实现的是:
我在一个目录中有大量的图像。我想为每张图片写一些描述。我准备了一个包含3列的DB表:id、image_name(唯一约束)和description。为了让它发挥作用,我开发了一个网页,在那里我会在浏览器中打开每个图像,写下关于它的描述,保存到数据库中,然后通过点击下一个打开下一个图像,以此类推
然而,我不知道如何实现它
$dir = "/images/";
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
closedir($dh);
}
}
然后,在到达第n个图像之前,我总是打开n-1个图像。
我将首先将文件导入数据库。不是实际的文件,只是对文件夹中文件的引用。(这不是完整的代码,但你会明白的)
$files = array_diff( scandir("/path/to/directory"), array(".", "..") );
foreach($files as $file) {
//insert a reference into the database
$query = "insert into table_name (image_name) values $file;";
mysql_query($query);
}
一旦它们就位,您就可以通过Id.轻松查询它们
一个网页看起来像这样:
<?php
$imageId= (int)$_GET['id'];
$row = mysql_fetch_array("select * from table_name where id=$imageId");
?>
<html><body>
<a href="?id=<?php echo $imageId + 1; ?>"> Next image </a>
<img src="<? echo $row['image_name']; ?> ">
your form here...
并使用例如http://127.0.0.1/images/index.php?id=1
使用浏览器无法执行此操作,因为在web请求之间PHP不会保持其状态。
你能做的是:
- 将最后一个图像编号保存在cookie中——在下一次请求时,您将读取它并跳到所需的编号(您仍然必须跳过)
- 将整个文件列表从PHP发送到浏览器,并使用Javascript和AJAX请求在一个页面内导航
- 将列表和/或数据库中的当前号码保存在某个临时表中。因此,每次将请求发送到PHP脚本时,它都会首先检查保存的数据是否存在
我要做的是找到一个数据库中不存在的图像,并请求对其进行描述,这将使php像:
if (!empty($_POST['image'])) {
// Save the image / description in the db
}
$existing = array(); // Fill this array with the image names that exist in the db.
$dir = "/images/";
// Open a directory, and read its contents
$file = null;
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if (!in_array($file, $existing)) {
break;
}
}
closedir($dh);
}
}
if ($file === null) {
die('something is wrong, I can not get any files');
}
// set the $file to your view
在html中,我会有这样的东西:
<form action="">
Image: <input name="image" type="text" value="<?php echo $file; ?>"/>
Description: <input name="description" type="text" value="<?php echo $file; ?>"/>
</form>