如何使用PHP上传图片并在网页上显示?

时间:2015-12-25 11:19:45

标签: php html

<body bgcolor = "pink">
<form method = "post" action = "" enctype = "mutlipart/form-data">
    <input type = "file" name="up" >
    <input type = "submit" value = "upload" name="submit">
    <input type = "reset" value = "clear">
</form>
<?php
if(isset($_POST['submit']))
{
//echo "<pre>";
//print_r($_FILES);
//echo "</pre>";
$name=addslashes($_FILES['up']['name']);
$image=addslashes($_FILES['up']['tmp_name']);
$image=file_get_contents($image);
$image=base64_encode($image);
echo $image;
$con = mysqli_connect("localhost", "root", "");
mysqli_select_db($con, "pic");
$res = mysqli_query($con , "INSERT INTO image(name, image) VALUES ('$name', '$image')");
if($res)
{
    echo "Image uploaded successfully";
}
else
{
    echo "Failed to save image in Database";
}
$qry = mysqli_query($con, "SELECT * FROM image");
echo "<table width = 450 border = 5 bordercolor = red align = center bgcolor = green cellpadding = 12>";
echo "<th>Sno</th>";
echo "<th>Name</th>";
echo "<th>Image</th>";
while ($row = mysqli_fetch_row($qry)) {
    $src = '<img width = 250 height = 125 src = "data:image; base64, '.$row[2].'">';
    echo "<tr>";
    echo "<th>".$row[0]."</th>";
    echo "<th>".$row[1]."</th>";
    echo "<th>".$src."</th>";
    echo "</tr>";
}
    echo "</table>";
         }
     ?>
</body>

我在这里使用图片上传并在表格中显示,我收到以下错误。

  • 注意:未定义的索引:在C:\ wamp \ www \ DMS \ image.php中

注意:这里我在同一页面中编写了PHP和HTML代码。

如何解决这个问题。请帮帮我

1 个答案:

答案 0 :(得分:1)

尝试

<body bgcolor = "pink">
<form method="post" action="" enctype="multipart/form-data">
    <input type="file" name="up">
    <input type="submit" value="Upload" name="submit">
    <input type = "reset" value = "clear">
</form>
<?php
    if(isset($_POST['submit']))
    {
    //echo "<pre>";
    //print_r($_FILES);
    //echo "</pre>";
    $name=addslashes($_FILES['up']['name']);
    $image=addslashes($_FILES['up']['tmp_name']);
    $image=file_get_contents($image);
    $image=base64_encode($image);
    echo $image;
    $con = mysqli_connect("localhost", "root", "");
    mysqli_select_db($con, "pic");
    $res = mysqli_query($con , "INSERT INTO image(name, image) VALUES ('$name', '$image')");
    if($res)
    {
        echo "Image uploaded successfully";
    }
    else
    {
        echo "Failed to save image in Database";
    }

    $qry = mysqli_query($con, "SELECT * FROM image");
    echo "<table width = 450 border = 5 bordercolor = red align = center bgcolor = green cellpadding = 12>";
    echo "<th>Sno</th>";
    echo "<th>Name</th>";
    echo "<th>Image</th>";
    while ($row = mysqli_fetch_row($qry))
    {
        $src = '<img width = 250 height = 125 src = "data:image; base64, '.$row[2].'">';
        echo "<tr>";
        echo "<th>".$row[0]."</th>";
        echo "<th>".$row[1]."</th>";
        echo "<th>".$src."</th>";
        echo "</tr>";
    }

    echo "</table>";
    }
    exit();
?>
</body>