我在显示可以上传到我的网站的图片时遇到问题。在上传过程中,我更改了文件名,将图片存储在文件夹中,并将文件名存储在数据库中。我在下面展示我的代码。非常感谢那些将要看看的人:
上传图片的表格:
<form method="post" action="PicPost.php" enctype="multipart/form-data">
<label for="Pic">Upload your pic: (JPG, JPEG PNG ou GIF | max. 1 Mo) :</label><br />
<input type="hidden" name="maxsize" value="1048576" />
<input type="file" name="Pic" id="Pic" />
<p>
<label>Tags
<input type="text" name="Tags" id="Tags" />
</label>
<br />
<input type="submit" name="submit" value="Submit" />
</p>
</form>
PicPost.php中完成上传的代码:
<?php
$maxsize = '1048576';
if ($_FILES['Pic']['error'] > 0) $erreur = "Error";
if ($_FILES['Pic']['size'] > $maxsize) $erreur = "The file is too big";
$extensions_valides = array( 'jpg' , 'jpeg' , 'gif' , 'png' );
$extension_upload = strtolower( substr( strrchr($_FILES['Pic'] ['name'], '.') ,1) );
if ( in_array($extension_upload,$extensions_valides) ) echo "Correct extension";
$name = md5(uniqid(rand(), true));
$resultat = move_uploaded_file($_FILES['Pic']['tmp_name'],$name);
if ($resultat) echo "Upload successful";
try
{
$bdd = new PDO('mysql:host=localhost;dbname=mydb', 'root', '');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$req = $bdd->prepare('INSERT INTO picdb (Picture, Tags)
VALUES(?, ?)');
$req->execute(array($name, $_POST['Tags']));
通过标签在数据库中搜索图片的代码:
<form id="form1" name="form1" method="post" action="SearchPost.php">
<label>
<input type="text" name="Search" id="Search" />
</label>
<label>
<input type="submit" name="Submit" id="Submit" value="Search" />
</label>
</form>
显示 SearchPost.php 中搜索到的图片的代码:
try
{
$bdd = new PDO('mysql:host=localhost;dbname=mydb', 'root', '');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$reponse = $bdd->query('SELECT Picture FROM picdb WHERE
Tags=\''.$_POST['Search'].'\'');
while ($donnees = $reponse->fetch())
echo "<img src=".$donnees['Picture']."/>";
$reponse->closeCursor();