【问题标题】:how to insert image and data in mysql database using php source code如何使用php源代码在mysql数据库中插入图像和数据
【发布时间】:2015-12-13 21:51:48
【问题描述】:

我正在尝试从 HTML 表单在我的数据库中插入图像和数据。我已经编写了 PHP 代码来完成这项任务。该程序没有生成任何错误消息,也没有在 MySQL 数据库中插入图像数据。请检查一下。在这里,我将分享我的代码的摘录。

 <?php

    error_reporting(E_ALL & ~E_NOTICE);
    @ini_set('post_max_size', '64M');
    @ini_set('upload_max_filesize', '64M');

    /* * *********************************************** */
    // database constants
    define('DB_DRIVER', 'mysql');
    define('DB_SERVER', 'localhost');
    define('DB_SERVER_USERNAME', 'remote');
    define('DB_SERVER_PASSWORD', 'remote123');
    define('DB_DATABASE', 'test');

    $dboptions = array(
        PDO::ATTR_PERSISTENT => FALSE,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
    );

    try {
      $DB = new PDO(DB_DRIVER . ':host=' . DB_SERVER . ';dbname=' . DB_DATABASE, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, $dboptions);
    } catch (Exception $ex) {
      echo $ex->getMessage();
      die;
    }

    if (isset($_POST["sub1"]) || isset($_POST["sub2"])) {
      // include resized library
      require_once('./php-image-magician/php_image_magician.php');
      $msg = "";
      $valid_image_check = array("image/gif", "image/jpeg", "image/jpg", "image/png", "image/bmp");
      if (count($_FILES["user_files"]) > 0) {
        $folderName = "uploads/";
        $sql = "INSERT INTO tbl_image (full_name, email, age, image_name) VALUES (:full_name, :email, :age, :img)";
       $stmt = $DB->prepare($sql);
        $query->bindParam(':full_name', $_POST['full_name'], PDO::PARAM_STR);
        $query->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
        $query->bindParam(':age', $_POST['age'], PDO::PARAM_STR);

        for ($i = 0; $i < count($_FILES["user_files"]["name"]); $i++) {

          if ($_FILES["user_files"]["name"][$i] <> "") {

            $image_mime = strtolower(image_type_to_mime_type(exif_imagetype($_FILES["user_files"]["tmp_name"][$i])));
            // if valid image type then upload
            if (in_array($image_mime, $valid_image_check)) {

              $ext = explode("/", strtolower($image_mime));
              $ext = strtolower(end($ext));
              $filename = rand(10000, 990000) . '_' . time() . '.' . $ext;
              $filepath = $folderName . $filename;

              if (!move_uploaded_file($_FILES["user_files"]["tmp_name"][$i], $filepath)) {
                $emsg .= "Failed to upload <strong>" . $_FILES["user_files"]["name"][$i] . "</strong>. <br>";
                $counter++;
              } else {
                $smsg .= "<strong>" . $_FILES["user_files"]["name"][$i] . "</strong> uploaded successfully. <br>";

                $magicianObj = new imageLib($filepath);
                $magicianObj->resizeImage(100, 100);
                $magicianObj->saveImage($folderName . 'thumb/' . $filename, 100);

                /*             * ****** insert into database starts ******** */
                try {
                  $stmt->bindValue(":img", $filename);
                  $stmt->execute();
                  $result = $stmt->rowCount();
                  if ($result > 0) {
                    // file uplaoded successfully.
                  } else {
                    // failed to insert into database.
                  }
                } catch (Exception $ex) {
                  $emsg .= "<strong>" . $ex->getMessage() . "</strong>. <br>";
                }
                /*             * ****** insert into database ends ******** */
              }
            } else {
              $emsg .= "<strong>" . $_FILES["user_files"]["name"][$i] . "</strong> not a valid image. <br>";
            }
          }
        }


        $msg .= (strlen($smsg) > 0) ? successMessage($smsg) : "";
        $msg .= (strlen($emsg) > 0) ? errorMessage($emsg) : "";
      } else {
        $msg = errorMessage("You must upload atleast one file");
      }
    }
    ?>
    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <link rel="icon" href="" type="image/x-icon" />
        <!--iOS/android/handheld specific -->
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="Upload multiple images create thumbnails and save path to database with php and mysql">
        <meta name="keywords" content="php, mysql, thumbnail,upload image, check mime type">
        <meta name="author" content="Shahrukh Khan">
        <title>Upload multiple images create thumbnails and save path to database with php and mysql - thesoftwareguy</title>
        <link rel="stylesheet" href="style.css" type="text/css" />
        <style>
          .files{height: 30px; margin: 10px 10px 0 0;width: 250px; }
          .add{ font-size: 14px; color: #EB028F; border: none; }
          .rem a{ font-size: 14px; color: #f00; border: none; }
          .submit{width: 110px; height: 30px; background: #6D37B0; color: #fff;text-align: center;}
        </style>
        <script src="jquery-1.9.0.min.js"></script>
        <script>
          $(document).ready(function() {
            $(".add").click(function() {
              $('<div><input class="files" name="user_files[]" type="file" ><span class="rem" ><a href="javascript:void(0);" >Remove</span></div>').appendTo(".contents");

            });
            $('.contents').on('click', '.rem', function() {
              $(this).parent("div").remove();
            });

          });
        </script>
      </head>
      <body>
        <div id="container">
          <div id="body">
            <div class="mainTitle" >Upload multiple images create thumbnails and save path to database with php and mysql</div>
            <div class="height20"></div>
            <article>
              <?php echo $msg; ?>
              <div class="height20"></div>
              <div style="width: 380px; margin: 0 auto;">
                <h3 style="text-align: center;">Image will be resized to 100px X 100px </h3>
                <form name="f1" action="index.php" method="post" enctype="multipart/form-data">            
                  <fieldset>
                    <legend>Demo1</legend>
                    Attach multiple Files:
                    <input class="files" name="user_files[]" type="file" multiple="multiple" >
                    <div class="height10"></div>
                    <div><input type="submit" class="submit" name="sub1" value="Upload Images" /> </div>
                  </fieldset> 
                </form>
                <div style="width: 380px; margin: 0 auto;">
                  <form name="f2" action="index.php" method="post" enctype="multipart/form-data">
                    <fieldset>
                      <legend>Demo2</legend>
                         <input type="text" id="full_name" class="frm_input" placeholder="Full name">
                        <input type="text" id="email" class="frm_input" placeholder="Email">
                        <input type="text" id="age" class="frm_input" placeholder="Age">
                      <input class="files" name="user_files[]" type="file" ><span><a href="javascript:void(0);" class="add" >Add More</a></span>
                      <div class="contents"></div>
                      <div class="height10"></div>
                      <div><input type="submit" class="submit" name="sub2" value="Upload Images" /> </div>
                    </fieldset>
                  </form>
                </div>
              </div>
              <div class="height10"></div>
              <?php
              // fetch all records
              $sql = "SELECT * FROM tbl_image WHERE 1 ";
              try {
                $stmt = $DB->prepare($sql);
                $stmt->execute();
                $images = $stmt->fetchAll();
              } catch (Exception $ex) {
                echo $ex->getMessage();
              }
              ?>
               <ul class="reorder_ul reorder-photos-list">
              <table class="bordered">
                <tr><th>ID</th><th>thumbnail</th><th>ORIGINAL</th></tr>
                <?php
                if (count($images) > 0) {
                  foreach ($images as $img) {
                    ?>


                      <li id="image_li_<?php echo $count; ?>" class="ui-sortable-handle">
                      <p><?php echo $img["image_name"]; ?></p>
                        <a href="uploads/<?php echo $img["image_name"]; ?>" target="_blank">
                          <img src="uploads/<?php echo $img["image_name"]; ?>" alt="<?php echo $img["image_name"]; ?>" width="300" height="300">
                        </a>
                        <p><?php echo $rs['full_name']; ?></p>
                    <p><?php echo $rs['email']; ?></p>
                    <p><?php echo $rs['age']; ?></p>
                    <p><a href="#" class="delete_m" onclick="delete_member(<?php echo $rs['id']; ?>)"><img src="images/delete.png"> Delete</a></td>
                      </li>

                    <?php
                  }
                } else {
                  ?>
                   <tr>
                  <td colspan="3">No images in the database.</td>
                </tr> 
                <?php } ?>
              </table>
               </ul>
              <div class="height10"></div>
            </article>
            <div class="height10"></div>
            <footer>
              <div class="copyright"> &copy; 2013 <a href="http://www.thesoftwareguy.in" target="_blank">thesoftwareguy</a>. All rights reserved </div>
              <div class="footerlogo"><a href="http://www.thesoftwareguy.in" target="_blank"><img src="http://www.thesoftwareguy.in/thesoftwareguy-logo-small.png" width="200" height="47" alt="thesoftwareguy logo" /></a> </div>
            </footer>
          </div>
        </div>

      </body>
    </html>
    <?php

    function errorMessage($str) {
      return '<div style="width:50%; margin:0 auto; border:2px solid #F00;padding:2px; color:#000; margin-top:10px; text-align:center;">' . $str . '</div>';
    }

    function successMessage($str) {
      return '<div style="width:50%; margin:0 auto; border:2px solid #06C;padding:2px; color:#000; margin-top:10px; text-align:center;">' . $str . '</div>';
    }
    ?>

【问题讨论】:

  • 与您的问题无关的代码太多。请检查stackoverflow.com/help/mcve 并更新您的问题。
  • Sunil,您在下面得到了答案。和他们一起去吧。我要离开这个问题。祝你好运。

标签: javascript php mysql ajax phpmyadmin


【解决方案1】:

你的文件字段应该是&lt;input type="file" name="img" multiple&gt;,我希望你不会遇到任何问题。

【讨论】:

  • 不正确。阅读手册php.net/manual/en/features.file-upload.multiple.phpmultiple="multiple" 有效。你错过了什么。
  • 这不是官方的 PHP.net 文档。 w3学校很糟糕。如果 OP 同意你的话,我会吃掉我的短裤。成交?
  • “两者都将以相同的方式工作” - 你在自相矛盾。看看 OP 已经在使用什么 &lt;input class="files" name="user_files[]" type="file" multiple="multiple" &gt; 唯一我可以说“可能”失败的是他们的 JS 版本中的一个 $('&lt;div&gt;&lt;input class="files" name="user_files[]" type="file" &gt; 但我对此表示怀疑。
  • 尝试在两者上工作,你不会发现它们之间有任何区别。只需在您这边测试一下,您就会清楚
  • 我现在刚刚测试,两种输入类型都可以正常工作。我并不矛盾。如果您认为我对这个答案有误,我建议您在您这边测试一下。
【解决方案2】:
   insert image and data in mysql database using php source code and view the images.  



 <?php


            $images_arr = array();
                //This is the directory where images will be saved
            $target_dir = "uploads/";
            $target = $target_dir.$_FILES['photo']['name'];

                //$target = $target . basename( $_FILES['photo']['name']);

                //This gets all the other information from the form
            $name=$_POST['nameMember'];
            $bandMember=$_POST['bandMember'];
            $pic=($_FILES['photo']['name']);
            $about=$_POST['aboutMember'];
            $bands=$_POST['otherBands'];


                // Connects to your Database
            mysql_connect("Localhost", "remote", "remote123") or die(mysql_error()) ;
            mysql_select_db("test") or die(mysql_error()) ;

                //Writes the information to the database
            mysql_query("INSERT INTO dbProfiles (nameMember,bandMember,photo,aboutMember,otherBands)
            VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;

            //Writes the photo to the server
            if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)){

                    //Tells you if its all ok
                echo "The file ". $target_dir.$_FILES['photo']['name']. " has been uploaded, and your information has been added to the directory";
                $images_arr[] = $target;
            }
            else {

                //Gives and error if its not
                echo "Sorry, there was a problem uploading your file.";
            }

    ?>
    <!DOCTYPE html>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <link rel="icon" href="http://www.thesoftwareguy.in/favicon.ico" type="image/x-icon" />
                    <!--iOS/android/handheld specific -->
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta name="description" content="Upload multiple images create thumbnails and save path to database with php and mysql">
            <meta name="keywords" content="php, mysql, thumbnail,upload image, check mime type">
            <meta name="author" content="Shahrukh Khan">
            <title>Upload multiple images create thumbnails and save path to database with php and mysql </title>
            <link rel="stylesheet" href="style.css" type="text/css" />
            <style>
                 .files{height: 30px; margin: 10px 10px 0 0;width: 250px; }
                .add{ font-size: 14px; color: #EB028F; border: none; }
                .rem a{ font-size: 14px; color: #f00; border: none; }
                .submit{width: 110px; height: 30px; background: #6D37B0; color: #fff;text-align: center;}
            </style>
            <script src="jquery-1.9.0.min.js"></script>
            <script>
                $(document).ready(function() {
                    $(".add").click(function() {
                    $('<div><input class="files" name="user_files[]" type="file" ><span class="rem" ><a href="javascript:void(0);" >Remove</span></div>').appendTo(".contents");

                    });
                    $('.contents').on('click', '.rem', function() {
                    $(this).parent("div").remove();
                    });

                });
            </script>
        </head>
        <body>
            <form name="f1" action="index.php" method="post" enctype="multipart/form-data">  
                <input type="hidden" name="image_form_submit" value="1"/>
                    <div id="container">
                        <div id="body">
                            <div class="mainTitle" >Upload multiple images create thumbnails and save path to database with php and mysql</div>
                            <div class="height20"></div>
                            <article>
                                <div class="height20"></div>
                                <div style="width: 380px; margin: 0 auto;">
                                    <h3 style="text-align: center;">Image will be resized to 100px X 100px </h3>

                                    <p>Please Enter the Band Members Name.</p>
                                    <p> Band Member or Affiliates Name:</p>
                                    <input type="text" name="nameMember"/>
                                    <p>
                                         Please Enter the Band Members Position. Example:Drums.
                                    </p>
                                     <p>
                                        Band Position:
                                     </p>
                                    <input type="text" name="bandMember"/>
                                    <p>
                                        Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb.
                                    </p>
                                    <p>
                                        Photo:
                                    </p>
                                    <input type="hidden" name="size" value="350000">
                                    <input type="file" name="photo"> 
                                <p>
                                    Please Enter any other information about the band member here.
                                </p>
                                <p>
                                     Other Member Information:
                                </p>
                                <textarea rows="10" cols="35" name="aboutMember">
                                </textarea>
                                 <p>
                                     Please Enter any other Bands the Member has been in.
                                 </p>
                                <p>
                                         Other Bands:
                                </p>
                                    <input type="text" name="otherBands" size=30 />
                                <br/>
                                <br/>
                                    <input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/>




                            </div>
                            <table class="bordered">
                             <?php
              // fetch all records
              $sql = "SELECT * FROM dbProfiles WHERE 1 "; ?>
              <?php
             $sql="SELECT * FROM dbProfiles";
     $result_set=mysql_query($sql);
     while($row=mysql_fetch_array($result_set))
     {
      ?>
            <tr>
           <td><p><?php echo $row['nameMember'] ?>"</p></td>
            <td><img src="uploads/<?php echo $row['photo'] ?>" width="200px" height="200px;"/><p><?php echo $row['nameMember'] ?>"</p></td>
            </tr>
            <?php
     }
     ?>
     </table>

                        </article>
                    </div>

                </div>
                <div class="height10"></div>

        </form>

      </body>
    </html>
    <?php

    function errorMessage($str) {
      return '<div style="width:50%; margin:0 auto; border:2px solid #F00;padding:2px; color:#000; margin-top:10px; text-align:center;">' . $str . '</div>';
    }

    function successMessage($str) {
      return '<div style="width:50%; margin:0 auto; border:2px solid #06C;padding:2px; color:#000; margin-top:10px; text-align:center;">' . $str . '</div>';
    }
    ?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    相关资源
    最近更新 更多