2014-02-16 155 views
5

我有一个问题插入图像在我的数据库中的基本形式。有两种形式,一种插入类别(图像和名称),另一种插入位置(名称,地址,图像等)。 add_category函数工作正常,它不是add_location,并且特别插入图像。我相信它会插入有问题的图像。无法将图像插入数据库

问题是,如果插入图像中的if语句永远不会执行,我不知道为什么。它在检查图像if语句下的功能add_location(..)中。

if ($result = $this->mysqli->query($query)) { 
    $error['result'] = $this->succAddLoc; 
} 

我删除了文件中不必要的功能:

<?php 
    class pongodev { 
     var $mysqli; 

     // Error handling variables 
     var $errCatName; 
     var $errLatitude; 
     var $errLongitude; 
     var $errImage; 
     var $errPhone; 
     var $errWebsite; 
     var $succAddLoc; 
     var $succAddCat; 
     var $errEmail; 
     var $errPass; 
     var $succPass; 
     var $succEmail; 
     var $succEmailPass; 
     var $succResetPass; 
     var $errResetPass; 
     var $errUsername; 

     // Email configuration variables 
     var $emailSubject; 
     var $resetMessage; 
     var $from; 
     var $adminEmail; 


     // Connect to database 
     function __construct($host, $user, $pass, $database){ 
      // Connect to database 
      $this->mysqli = new mysqli($host, $user, $pass, $database); 

      if(mysqli_connect_errno($this->mysqli)){ 
       echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
      } 

     } 

     // Close database 
     function close_database(){ 
      $this->mysqli->close(); 
     } 

     // Validate username and password 
     function validate_user($username, $password){ 
      ...... 
     } 

     // Error handling label for reset password form 
     function fill_error_pass($succResetPass, $errResetPass, $errUsername){ 
      ...... 
     } 

     // Email message configuration 
     function email_configuration($emailSubject, $resetMessage, $from, $adminEmail){ 
     ..... 
     } 

     // Reset password 
     function reset_password($username){ 
     ..... 
     } 

     // Error handling label for add new location form 
     function fill_error_location_data($errLatitude, $errLongitude, $errPhone, $errWebsite, 
           $errImage, $succAddLoc){ 
      $this->errLatitude = $errLatitude; 
      $this->errLongitude = $errLongitude; 
      $this->errPhone = $errPhone; 
      $this->errWebsite = $errWebsite; 
      $this->errImage = $errImage; 
      $this->succAddLoc = $succAddLoc; 

     } 

     // Add new location 
     function add_location($locationName, $address, $category, 
          $locImage, $lat, $lng, $tel, $url, $desc){ 

      // Create array variables to store multiple error 
      $error = array(); 

      // Check if latitude is float 
      $floatLat = floatVal($lat); 
      if(!($floatLat && intVal($floatLat) != $floatLat)){ 
       $error['latitude'] = $this->errLatitude; 
      } 

      // Check if Longitude is float 
      $floatLng = floatVal($lng); 
      if(!($floatLng && intVal($floatLng) != $floatLng)){ 
       $error['longitude'] = $this->errLongitude; 
      } 

      // Validate phone number 
      if(empty($tel) || ($tel == "-")){ 
       $tel = "-"; 
      }else{ 
       $phonePattern = "/^[0-9()-]+$/"; 
       if(!preg_match($phonePattern, $tel)){ 
        $error['phone'] = $this->errPhone; 
       } 
      } 

      // Validate website 
      if(empty($url) || ($url == "-")){ 
       $url = "-"; 
      }else{ 
       $urlPattern = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i"; 
       if (!preg_match($urlPattern, $url)){ 
        $error['website'] = $this->errWebsite; 
       } 
      } 

      // Check image file 
      $allowedExts = array("jpeg", "jpg"); 
      $temp = explode(".", $locImage["name"]); 
      $extension = end($temp); 
      if (((($locImage["type"] == "image/jpeg") 
      || ($locImage["type"] == "image/jpg")) 
      || ($locImage["type"] == "image/pjpeg")) 
      && ($locImage["size"] < 700000) 
      && in_array($extension, $allowedExts) 
      && !isset($error['latitude']) && !isset($error['longitude']) && !isset($error['phone']) && !isset($error['website'])){ 


        // Create random image file name 
        $string = ''; 
        $file = preg_replace("/\s+/", "_", $locImage['name']); 
        $imageUpload = date("Y-m-d")."-".$this->get_random_string($string, 4).".".$extension; 

        // Copy file to server directory 
        move_uploaded_file($locImage["tmp_name"], 
        "upload/images/" . $imageUpload); 
        $imageUpload = "upload/images/". $imageUpload; 

        $locationDate = date("Y-m-d"); 

        // Add location data to tbl_location 
        $query = "INSERT INTO tbl_location 
          (location_date, location_name, category_id, address, location_image, 
          latitude, longitude, phone, website, description) 
         VALUES ('$locationDate','$locationName', '$category', '$address', '$imageUpload', 
          $lat, $lng, '$tel', '$url', '$desc')"; 



       if($result = $this->mysqli->query($query)){ 

        $error['result'] = $this->succAddLoc; 
       } 

      }else{ 

       $error['image'] = $this->errImage; 

      } 


      return $error; 
     } 

     // Get all locations data 
     function get_all_locations(){ 

      ..... 
     } 

     // Get all locations data for map 
     function get_all_locations_map(){ 
     ..... 
     } 

     // Get location data by id 
     function get_location_by_id($id, $tag){ 
      ..... 
     } 

     // Get location data to be displayed on location view page 
     function get_location_view($id){ 

       // Get all locations data from tbl_location 
       $query = "SELECT location_name, category_name, category_marker, address, location_image, latitude, longitude, phone, website, description 
         FROM tbl_location l, tbl_categories c 
         WHERE (l.category_id = c.category_id) AND (l.location_id = ?)"; 


       $stmt = $this->mysqli->stmt_init(); 
       if($stmt->prepare($query)) {  
        // Bind your variables to replace the ?s 
        $stmt->bind_param('s', $id); 
        // Execute query 
        $stmt->execute(); 
        // store result 
        $stmt->store_result(); 
        $stmt->bind_result($data['location_name'], 
          $data['category_name'], 
          $data['category_marker'], 
          $data['address'], 
          $data['location_image'], 
          $data['latitude'], 
          $data['longitude'], 
          $data['phone'], 
          $data['website'], 
          $data['description'] 
          ); 
        $stmt->fetch(); 
        $stmt->close(); 
       } 

      return $data; 
     } 

     // Delete location data 
     function delete_location($id){ 
      ...... 

     } 

     // Add new location 
     function update_location($id, $locationName, $address, $category, 
          $locImage, $lat, $lng, $tel, $url, $desc, $previousImage){ 

      // Create array variables to handle multiple errors 
      $error = array(); 

      // Check if latitude is float 
      $floatLat = floatVal($lat); 
      if(!($floatLat && intVal($floatLat) != $floatLat)){ 
       $error['latitude'] = $this->errLatitude; 
      } 

      // Check if Longitude is float 
      $floatLng = floatVal($lng); 
      if(!($floatLng && intVal($floatLng) != $floatLng)){ 
       $error['longitude'] = $this->errLongitude; 
      } 

      // Validate phone number 
      if(empty($tel) || ($tel == "-")){ 
       $tel = "-"; 
      }else{ 
       $phonePattern = "/^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$/"; 
       if(!preg_match($phonePattern, $tel)){ 
        $error['phone'] = $this->errPhone; 
       } 
      } 

      // Validate url 
      if(empty($url) || ($url == "-")){ 
       $url = "-"; 
      }else{ 
       $urlPattern = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i"; 
       if (!preg_match($urlPattern, $url)){ 
        $error['website'] = $this->errWebsite; 
       } 
      } 

      // Check image location 
      if(empty($locImage['name'])){ 
       if(!isset($error['latitude']) && !isset($error['longitude']) && !isset($error['phone']) && !isset($error['website'])){ 

        // Add location data to database 
        $query = "UPDATE tbl_location 
          SET location_name = '$locationName', 
           category_id = '$category', 
           address = '$address', 
           latitude = '$lat', 
           longitude = '$lng', 
           phone = '$tel', 
           website = '$url', 
           description = '$desc' 
          WHERE location_id = '$id'"; 

        if($result = $this->mysqli->query($query)){ 
         $error['result'] = $this->succAddLoc; 
        } 

       } 
      }else{ 
       // Check image file 
       $allowedExts = array("jpeg", "jpg"); 
       $temp = explode(".", $locImage["name"]); 
       $extension = end($temp); 
       if (((($locImage["type"] == "image/jpeg") 
       || ($locImage["type"] == "image/jpg")) 
       || ($locImage["type"] == "image/pjpeg")) 
       && ($locImage["size"] < 700000) 
       && in_array($extension, $allowedExts) 
       && !isset($error['latitude']) && !isset($error['longitude']) && !isset($error['phone']) && !isset($error['website'])){ 

         // Create random image file name 
         $string = ''; 
         $file = preg_replace("/\s+/", "_", $locImage['name']); 
         $imageUpload = date("Y-m-d")."-".$this->get_random_string($string, 4).".".$extension; 

         // Copy file to server directory 
         move_uploaded_file($locImage["tmp_name"], 
         "upload/images/" . $imageUpload); 
         $imageUpload = "upload/images/". $imageUpload; 

         // Delete previous image 
         $delete = unlink("$previousImage"); 

         // Add location data to database 
         $query = "UPDATE tbl_location 
           SET location_name = '$locationName', 
            category_id = '$category', 
            address = '$address', 
            location_image = '$imageUpload', 
            latitude = '$lat', 
            longitude = '$lng', 
            phone = '$tel', 
            website = '$url', 
            description = '$desc' 
           WHERE location_id = '$id'"; 

        if($result = $this->mysqli->query($query)){ 
         $error['result'] = $this->succAddLoc; 
        } 

       }else{ 
        $error['image'] = $this->errImage; 

       } 
      } 

      return $error; 
     } 

     // Error handling label 
     function fill_error_category_data($errCatName, $errImage, $succAddCat){ 
      $this->errImage = $errImage; 
      $this->errCatName = $errCatName; 
      $this->succAddCat = $succAddCat; 
     } 

     // Delete category 
     function delete_category($id){ 
      ...... 

     } 

     // Add new category 
     function add_category($categoryName, $markerImage){ 

      // Get category data from tbl_categories 
      $query = "SELECT * FROM tbl_categories 
         WHERE category_name = '$categoryName'"; 

      if($result = $this->mysqli->query($query)){ 
       $row = $result->num_rows; 
       $result->close(); 
      } 

      // Create array variables to handle multiple array 
      $error = array(); 

      // If category already exist in tbl_categories set the error 
      if($row > 0){ 
       $error['name'] = $this->errCatName; 
      } 

      list($width, $height, $type, $attr) = getimagesize($markerImage["tmp_name"]); 

      $allowedExts = array("png"); 
      $temp = explode(".", $markerImage["name"]); 
      $extension = end($temp); 
      if ((($markerImage["type"] == "image/x-png") 
      || ($markerImage["type"] == "image/png")) 
      && ($markerImage["size"] < 100000) 
      && in_array($extension, $allowedExts) 
      && (($width == 64) && ($height == 64)) 
      && !isset($error['name'])){ 

        // Create random image file name 
        $string = ''; 
        $file = preg_replace("/\s+/", "_", $markerImage['name']); 
        $imageUpload = date("Y-m-d")."-".$this->get_random_string($string, 4).".".$extension; 
        // Copy image to server directory 
        move_uploaded_file($markerImage["tmp_name"], 
        "upload/markers/" . $imageUpload); 
        $imageUpload = "upload/markers/". $imageUpload; 

        // Add category to database 
       $query = "INSERT INTO tbl_categories 
          (category_name, category_marker) 
         VALUES ('$categoryName', '$imageUpload')"; 

       if($result = $this->mysqli->query($query)){ 
        debug_to_console($query); 
        $error['result'] = $this->succAddCat; 
       } 

      }else{ 
       $error['marker'] = $this->errImage; 
      } 


      return $error; 
     } 

     // Get all categories data 
     function get_all_categories(){ 

      // Get categories data from database 
      $query = "SELECT * FROM tbl_categories 
         ORDER BY category_id"; 

      $result = $this->mysqli->query($query); 

      return $result; 
     } 

     // Get category data 
     function get_category_by_id($id){ 
      ..... 
     } 

     // Update category data 
     function update_category($id, $previousName, $categoryName, $categoryMarker, $previousMarker){ 

      ....... 

    } 

     // Create random name for image file 
     function get_random_string($valid_chars, $length){ 

      $random_string = ""; 
      $num_valid_chars = strlen($valid_chars); 

      for ($i = 0; $i < $length; $i++){ 
       $random_pick = mt_rand(1, $num_valid_chars); 
       $random_char = $valid_chars[$random_pick-1]; 
       $random_string .= $random_char; 
      } 

      return $random_string; 
     } 

     // Error handling label 
     function fill_error_settings($errEmail, $errPass, $succPass, $succEmail, $succEmailPass){ 
      $this->errEmail = $errEmail; 
      $this->errPass = $errPass; 
      $this->succPass = $succPass; 
      $this->succEmail = $succEmail; 
      $this->succEmailPass = $succEmailPass; 
     } 

     // Settings 
     function settings($user, $email, $newPass, $confirmPass){ 

      ..... 
     } 

    } 
?> 

这里是add_location_form.php

<?php 
    include('variables/variables.php'); 
    include('libs/pongodev.php'); 


    // Create object of pongodev class 
    $objMap = new pongodev($host, $userdb, $passdb, $database); 

    $result = 9999; 

    // Get all category name 
    $resultCategory = $objMap->get_all_categories(); 

    // Initialize location data 
    $locationName = ''; 
    $address = ''; 
    $category = ''; 
    $image = ''; 
    $latitude = ''; 
    $longitude = ''; 
    $phone = ''; 
    $website = ''; 
    $description = ''; 

    // When user click on Submit button 
    if(isset($_POST['btnSubmit'])){ 

     // Get location data 
     $locationName = $_POST['locationName']; 
     $address = $_POST['address']; 
     $category = $_POST['category']; 
     $image = $_FILES['image']; 
     $latitude = $_POST['latitude']; 
     $longitude = $_POST['longitude']; 
     $phone = $_POST['phone']; 
     $website = $_POST['website']; 
     $description = $_POST['description']; 

     // Create array variables 
     $result = array(); 

     // Fill error label 
     $objMap->fill_error_location_data($lblErrLatitude, $lblErrLongitude, $lblErrPhone, $lblErrWebsite, $lblErrImage, $lblAddLocSuccess); 

     // Add location data to database 
     $result = $objMap->add_location($locationName, $address, $category, 
             $image, $latitude, $longitude, 
             $phone, $website, $description); 

    } 
?> 

<div class="content-container"> 
    <div class="row heading-container"> 
     <div class="col-xs* col-md-9"> 
     <h1><?php echo $lblAddNewLocation; ?></h1> 
     </div> 
    </div><!--/heading-container--> 

<div class="clear"></div> 

<form class="form-horizontal" role="form" method="post" enctype="multipart/form-data"> 

    <!-- Location name form --> 
    <div class="form-group"> 
     <label for="inputLocationName" class="col-sm-2 control-label"><?php echo $lblName; ?></label> 
     <div class="col-sm-10"> 
      <input type="text" class="form-control" id="inputLocationName" name="locationName" placeholder="<?php echo $lblName; ?>" value="<?php echo $locationName; ?>" required focus> 
     </div><!--/span--> 
    </div><!--/form-group--> 
    <!--/Location name form --> 

    <!-- Address form --> 
    <div class="form-group"> 
     <label for="inputAddress" class="col-sm-2 control-label"><?php echo $lblAddress; ?></label> 
     <div class="col-sm-10"> 
      <input type="text" class="form-control" id="inputAddress3" name="address" placeholder="<?php echo $lblAddress; ?>" value="<?php echo $address; ?>" required> 
     </div><!--/span--> 
    </div><!--/form-group--> 
    <!--/Address form --> 

    <!-- Category form --> 
    <div class="form-group"> 
     <label for="inputCategory" class="col-sm-2 control-label"><?php echo $lblCategory; ?></label> 
     <div class="col-sm-10"> 
      <select class="form-control" id="inputCategory" name="category" required> 

       <?php while($data = mysqli_fetch_array($resultCategory)){ 
        if($data['category_id'] == $category){?>        
         <option value="<?php echo $data['category_id']; ?>" selected><?php echo $data['category_name']; ?></option> 
        <?php }else{ ?> 
         <option value="<?php echo $data['category_id']; ?>"><?php echo $data['category_name']; ?></option> 
       <?php } 
       }?> 
      </select> 
     </div><!--/span--> 
    </div><!--/form-group--> 
    <!--/Category form --> 

    <!-- Latitude form --> 
    <?php echo isset($result['latitude']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?> 
     <label for="inputLatitude" class="col-sm-2 control-label"><?php echo $lblLatitude; ?></label> 
     <div class="col-sm-10"> 
      <input type="text" class="form-control" id="inputLatitude" name="latitude" placeholder="<?php echo $lblLatitude; ?>" value="<?php echo $latitude; ?>" required> 
      <span class="help-block"><em><?php echo isset($result['latitude']) ? $result['latitude']." ".$lblLatitudeHelp : $lblLatitudeHelp; ?></em></span> 
     </div><!--/span--> 
    </div><!--/form-group--> 
    <!--/Latitude form --> 

    <!-- Longitude form --> 
    <?php echo isset($result['longitude']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?> 
     <label for="inputLongitude" class="col-sm-2 control-label"><?php echo $lblLongitude; ?></label> 
     <div class="col-sm-10"> 
      <input type="text" class="form-control" id="inputLongitude" name="longitude" placeholder="<?php echo $lblLongitude; ?>" value="<?php echo $longitude; ?>" required> 
      <span class="help-block"><em><?php echo isset($result['longitude']) ? $result['longitude']." ".$lblLongitudeHelp : $lblLongitudeHelp; ?></em></span> 
     </div><!--/span--> 
    </div><!--/form-group--> 
    <!--/Longitude form --> 

    <!-- Image form --> 
    <?php echo isset($result['image']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?> 
     <label for="inputImage" class="col-sm-2 control-label"><?php echo $lblImage; ?></label> 
     <div class="col-sm-10"> 
      <input type="file" class="form-control" id="inputImage" name="image" required> 
      <span class="help-block"><em><?php echo isset($result['image']) ? $result['image']." ".$lblImageHelp : $lblImageHelp; ?></em></span> 
     </div><!--/span--> 
    </div><!--/form-group--> 
    <!--/Image form --> 

    <!-- Phone form --> 
    <?php echo isset($result['phone']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?> 
     <label for="inputPhone" class="col-sm-2 control-label"><?php echo $lblPhone; ?></label> 
     <div class="col-sm-10"> 
      <input type="tel" class="form-control" id="inputPhone" name="phone" placeholder="<?php echo $lblPhone; ?>" value="<?php echo $phone; ?>"> 
      <span class="help-block"><em><?php echo isset($result['phone']) ? $result['phone']." ".$lblPhoneHelp : $lblPhoneHelp; ?></em></span> 
     </div><!--/span--> 
    </div><!--/form-group--> 
    <!--/Phone form --> 

    <!-- Website form --> 
    <?php echo isset($result['website']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?> 
     <label for="inputWebsite" class="col-sm-2 control-label"><?php echo $lblWebsite; ?></label> 
     <div class="col-sm-10"> 
      <input type="text" class="form-control" id="inputWebsite" name="website" placeholder="<?php echo $lblWebsite; ?>" value="<?php echo $website; ?>"> 
      <span class="help-block"><em><?php echo isset($result['website']) ? $result['website']." ".$lblWebsiteHelp : $lblWebsiteHelp; ?></em></span> 
     </div><!--/span--> 
    </div><!--/form-group--> 
    <!--/Website form --> 

    <!-- Description --> 
    <div class="form-group"> 
     <label for="inputDescription" class="col-sm-2 control-label"><?php echo $lblDescription; ?></label> 
     <div class="col-sm-10"> 
      <textarea class="form-control" rows="3" id="inputDescription" name="description" placeholder="Description" required><?php echo $description; ?></textarea> 
     </div><!--/span--> 
    </div><!--/form-group--> 
    <!--/Description --> 

    <!-- if add data success show success alert, otherwise display error alert --> 
    <?php if($result != 9999){ 
     if(isset($result['result'])){ ?> 
     <div class="alert alert-success alert-dismissable"> 
      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> 
      <p><?php echo $result['result']; ?></p> 
     </div> 
    <?php }else{ ?> 
     <div class="alert alert-danger alert-dismissable"> 
      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> 
      <p><?php echo $lblErrData; ?></p> 
     </div> 
    <?php }} ?> 
    <!--/Adding result --> 

    <!-- Submit button --> 
    <div class="form-group"> 
     <div class="col-sm-offset-2 col-sm-10"> 
       <button type="reset" class="btn btn-default"><?php echo $lblReset; ?></button> 
       <button type="submit" class="btn btn-primary" name="btnSubmit"><?php echo $lblSubmit; ?></button> 
     </div><!--/span--> 
    </div><!--/form-group--> 
    <!--/Submit button --> 

    </form> 
</div><!--/contain-container--> 

<?php $objMap->close_database(); ?> 
+1

如果if()永远不会被执行,然后查看它之前的代码并找出原因。你也不会说如果不工作 - 你在这段代码中有很多......我们不打算通读一段代码来尝试和猜测你正在谈论哪个部分。 –

+0

@MarcB感谢您的评论。它在//检查图像文件下的函数add_location中。我编辑了我的问题。我查看了if语句之前的内容,并没有发现任何错误,这与我用于add_category的代码相同,可以正常工作。 –

+0

一个很好的做法是放弃W3fools上传处理代码....来自该网站的PHP代码应该被视为核废料。 –

回答

0

尝试这种$image = $_FILES['image']['name'];代替$image = $_FILES['image'];

1

替换:

$ image = $ _FILES ['image'];

$图像= $ _FILES [ '图像'] [ '名称'];

,如果你想图像名称
或:
有:

$图像= $ _FILES [ '形象'] [ 'tmp_name的值'];


如果你指的是文件

0

$ _FILES [“形象”]包含像名称,类型,大小,误差,不对tmp_name上传文件的所有相关信息的数组,所以无论datat你想你需要调用,如:

$ _FILES [ '形象'] [ '名'] $ _FILES [ '形象'] [ '型']等

希望这有助于你... :)

0

插入Imag es进入你的数据库不是一个好主意。建议将上传的图像移动到指定的目录中,并将图像的路径保存到数据库中。

0

只是做以下..

$image=$_FILES['image']['name']; 

采取上述方式$图像变量的值,相信你们的问题将得到解决。