【问题标题】:How to add image upload in php and mysql?如何在php和mysql中添加图片上传?
【发布时间】:2014-03-15 16:22:21
【问题描述】:

如何在此代码中添加图片上传?这是您编写新闻的代码。我想在这段代码中添加图片上传,这样我就可以用图片写一篇新闻了。它现在只打印文本。

<?php
        if ( !isset($database_link))
        {
            die(header('location: index.php?page=news'));
        }
        if ( !isset($_GET['category_id']))
        {
            die(header('location: index.php?page=news'));
        }
        $category_id = ($_GET['category_id'] * 1);



        $news_title = '';
        $news_content = '';
        $user_id = $_SESSION['user']['user_id'];


        if (isset($_POST['news_submit']))
        {
            $form_ok = true;

            $news_title = mysqli_real_escape_string($database_link, $_POST['news_title']);
            $news_content = mysqli_real_escape_string($database_link, $_POST['news_content']);




            if ($news_title == '')
            {
                $form_ok = false;
                echo '<p class="alert alert-error">Please complete</p>';
            }
            if ($news_content == '')
            {
                $form_ok = false;
                echo '<p class="alert alert-error">Please complete</p>';
            }


                    if ($form_ok) 

            {
                $query = "
                    INSERT INTO news 
                        (news_title, news_content, news_postdate, fk_users_id, fk_categories_id) 
                    VALUES 
                        ('$news_title','$news_content', NOW(), '$user_id', '$category_id')";
                $result = mysqli_query($database_link, $query) or if_sql_error_then_die(mysqli_error($database_link), $query);

                if ($result)
                {
                    generateRss($category_id);
                    die(header('location: index.php?page=news&category_id='.$category_id));
                }
            }
        }
    ?>

    <div class="col-lg-12">
      <form method="post" role="form">
        <div class="form-group">
          <label for="news_title">News Titel</label>
          <input type="text" class="form-control" name="news_title" id="news_title" placeholder="Nyheds Titel" value="<?php echo $news_title; ?>" maxlength="64" required>
        </div>
        <div class="form-group ">
          <label for="news_content">News text</label>
          <textarea class="form-control" id="editor1" name="news_content" placeholder="Nyheds Tekst" rows="10" cols="80" required>

                </textarea>
          <script>

                    CKEDITOR.replace( 'editor1' );
                </script> 
        </div>
        <div class="form-group">
          <label for="category_id">News</label>
          <select class="form-control-select" name="category_id" id="category_id">
            <option value="0">Choose News</option>
            <?php
                        $query = "SELECT category_id, category_title FROM categories ORDER BY category_title ASC";
                        $result = mysqli_query($database_link, $query) or if_sql_error_then_die(mysqli_error($database_link), $query);
                        if (mysqli_num_rows($result) > 0)
                        {
                            while ($row = mysqli_fetch_assoc($result))
                            {
                                $selected = ($category_id == $row['category_id'] ? ' selected="selected"' : '');
                                echo '<option value="'.$row['fk_categories_id'].'"'.$selected.'>'.$row['category_title'].'</option>';
                            }
                        }
                    ?>
          </select>
        </div>
        <input type="submit" class="btn-send" style="background-color:#D67400; border-color:#D67400;" name="news_submit" value="Gem" />
        <a href="index.php?page=news&amp;category_id=<?php echo $category_id; ?>" class="btn btn-default" onclick="return confirm('Are you sure you want to cancel?')">Annuller</a>
      </form>
    </div>

这是它从数据库中获取然后在其上打印图像的代码。如您所见,它只打印没有图片的文本。

 <?php
    if ( !isset($database_link))
    {
        die(header('location: index.php'));
    }

    > $query = "  SELECT news_id, news_title, news_content, news_postdate,
    > category_id, category_title, user_name 
    >               FROM news
    >               INNER JOIN categories ON categories.category_id = news.fk_categories_id
    >               INNER JOIN users ON users.user_id = news.fk_users_id
    >               ORDER BY news_postdate DESC
    >               LIMIT 10";
    >     $result = mysqli_query($database_link, $query) or if_sql_error_then_die(mysqli_error($database_link), $query);
    >     if (mysqli_num_rows($result) <= 0)
    >     {

        echo '  <p class="alert alert-info">emty...</p>';
    }
    else
    {

        while ($row = mysqli_fetch_assoc($result))
        {
            $news_id = $row['news_id'];
            $news_title = $row['news_title'];
            $news_content = substr(strip_tags($row['news_content']), 0, 200).'...';
            $news_postdate = strftime('%A d. %d. %B %Y  %H:%M', strtotime($row['news_postdate']));
            $user_name = $row['user_name'];
            $category_id = $row['category_id'];
            $category_title = $row['category_title'];
            echo '
                    <section class="news_category">
                        <h1>'.$news_title.'</h1>
                        <p1>  '.$news_postdate.' </p1>
                        <p><a href="index.php?page=news&amp;category_id='.$category_id.'&amp;news_id='.$news_id.'">'.$news_content.'</a></p>
                        <em> '.$user_name.', in category: '.$category_title.'</em><hr />
                    </section>';
                    echo '<div class="spacer"> </div>';
        }
    }

【问题讨论】:

标签: php mysql


【解决方案1】:

W3Schools 网站上有一个很好的教程。 它甚至显示代码。 现在不要把它作为一个公正的链接答案:

表格示例:

<html>
<body>

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html>

上传脚本:

<?php
if ($_FILES["file"]["error"] > 0)
  {
  echo "Error: " . $_FILES["file"]["error"] . "<br>";
  }
else
  {
  echo "Upload: " . $_FILES["file"]["name"] . "<br>";
  echo "Type: " . $_FILES["file"]["type"] . "<br>";
  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
  echo "Stored in: " . $_FILES["file"]["tmp_name"];
  }
?>

保存文件:

<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

【讨论】:

  • @andrew 虽然这个例子很棒。我的老师告诉我 w3schools 也很糟糕,但这个对我很有用。
【解决方案2】:

您需要在表单中添加enctype="multipart/form-data" 属性才能上传文件,并添加&lt;input type="file" name="file"/&gt; 输入

您可以使用$_FILES 变量检索上传的文件服务器端

这里有一些关于handling uploaded files的更有用的信息

编辑:

这是一个非常基本的示例,它不执行任何错误检查等。

<?php 
   if ($_SERVER['REQUEST_METHOD'] == 'POST') {
       move_uploaded_file($_FILES['file']['tmp_name'], realpath('../yourFilePath'));
   }
?>


<form  method="post" enctype="multipart/form-data">
  <input type="file" name="file"/>
  <input type="text" name="anotherInput">
</form>

【讨论】:

  • 你能告诉我具体怎么做吗?
  • @user3267128 查看编辑
猜你喜欢
  • 2021-03-30
  • 2016-07-20
  • 2012-07-19
  • 2015-01-17
  • 2013-01-23
  • 2012-07-03
  • 1970-01-01
  • 1970-01-01
  • 2013-03-27
相关资源
最近更新 更多