将图像文件保存在数据库和图像文件夹中

时间:2014-10-16 04:15:31

标签: php sql database image file-upload

我正在尝试同时保存图像数据库和图像文件夹中的图像,它保存在图像文件夹但不保存在数据库中的图像可以有人请帮助我不知道我做错了什么。

add.php

<?php
if (!defined('WEB_ROOT')) {
    exit;
}




$errorMessage = (isset($_GET['error']) && $_GET['error'] != '') ? $_GET['error'] : '&nbsp;';
?> 
<script>
function getXMLHTTP() { //fuction to return the xml http object
        var xmlhttp=false;  
        try{
            xmlhttp=new XMLHttpRequest();
        }
        catch(e)    {       
            try{            
                xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e){
                try{
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch(e1){
                    xmlhttp=false;
                }
            }
        }

        return xmlhttp;
    }



    function getCategory(strURL) {      

        var req = getXMLHTTP();

        if (req) {

            req.onreadystatechange = function() {
                if (req.readyState == 4) {
                    // only if "OK"
                    if (req.status == 200) {                        
                        document.getElementById('catdiv').innerHTML=req.responseText;                       
                    } else {
                        alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                    }
                }               
            }           
            req.open("GET", strURL, true);
            req.send(null);
        }

    }
</script>
<div class="content-box-header">
              <h3>Add New Restaurant</h3>
</div>              
<form action="processTopping.php?action=add" method="post" enctype="multipart/form-data" name="frmAddTopping" id="frmAddTopping">
 <table width="100%" border="0" align="center" cellpadding="5" cellspacing="1" class="entryTable">


  <tr>
    <td width="150" class="label">Restaurant  Name</td>
    <td class="content"><input name="txtName" class="text-input large-input" type="text" id="txtName" /></td>
  </tr>
  <tr>
    <td class="label">Restaurant  Email</td>
    <td class="content"><input name="txtEmail" class="text-input large-input" type="text" id="txtEmail" /></td>
  </tr>
  <tr>
    <td class="label">Restaurant  Phone</td>
    <td class="content"><input name="txtPhone" class="text-input large-input" type="text" id="txtPhone" /></td>
  </tr>
  <tr>
    <td class="label">Restaurant  Address</td>
    <td class="content"><input name="txtAddress" class="text-input large-input" type="text" id="txtAddress" /></td>
  </tr>
  <tr>
    <td class="label">Restaurant  Cuisine</td>
    <td class="content"><input name="txtCuisine" class="text-input large-input" type="text" id="txtCuisine" /></td>
  </tr>
  <tr>
    <td class="label">Restaurant  Mini Order</td>
    <td class="content"><input name="txtMini_order" class="text-input large-input" type="text" id="txtMini_order" /></td>
  </tr>
<tr>
    <td class="label">Restaurant  Suburbs</td>
    <td class="content"><input name="txtSuburbs" class="text-input large-input" type="text" id="txtSuburbs" /></td>
  </tr>
  <tr>
    <td width="150" class="label">Restaurant  Menu</td>
    <td class="content"><input name="txtMenu" class="text-input large-input" type="text" id="txtMenu" /></td>
  </tr>
  <tr>
    <td class="label">Restaurant  Reviews</td>
    <td class="content"><input name="txtReviews" class="text-input large-input" type="text" id="txtReviews" /></td>
  </tr>
  <tr>
    <td class="label">Restaurant  Logo</td>
    <td class="content"><input name="txtLogo" class="text-input large-input" type="text" id="txtLogo" /></td>
  </tr>
  <tr>
    <td class="label">Restaurant  Takeaway Hours</td>
    <td class="content"><input name="txtTakeawayHours" class="text-input large-input" type="text" id="txtTakeawayHours" /></td>
  </tr>
  <tr>
    <td class="label">Restaurant  Delivery Hours</td>
    <td class="content"><input name="txtDeliveryHours" class="text-input large-input" type="text" id="txtDeliveryHours" /></td>
  </tr>
  <tr>
    <td class="label">Restaurant  Map</td>
    <td class="content"><input name="txtMap" class="text-input large-input" type="text" id="txtMap" /></td>
  </tr>
<tr>
    <td class="label">Restaurant  Promotions</td>
    <td class="content"><input name="txtPromotions" class="text-input large-input" type="text" id="txtPromotions" /></td>
  </tr>

 <!-- <tr> 
   <td width="150" class="label">Image</td>
   <td class="content"> <input name="fleImage" type="file" id="fleImage" class="box">    </td>
  </tr>-->
  <tr>
    <td class="label" valign="middle">Images</td>
    <td  class="label">
        <div id="main">
          <table width="230" cellpadding="0">
            <tr>
              <td width="232" align="right">

              <input type="file" name="fleImage[]" /></td>
            </tr>
          </table>
        </div></td>
  </tr>

 </table>
 <p align="center"> 
  <input name="btnAddTopping" type="button" id="btnAddTopping" value="Add Restaurant" onClick="checkAddToppingForm();" class="button">
  &nbsp;&nbsp;<input name="btnCancel" type="button" id="btnCancel" value="Cancel" onClick="window.location.href='index.php';" class="button">  
 </p>
</form>

processTopping.php

<?php
require_once '../../library/config.php';
require_once '../library/functions.php';
error_reporting(E_ALL);
checkUser();

$action = isset($_GET['action']) ? $_GET['action'] : '';

switch ($action) {

    case 'add' :
        addTopping();
        break;

    case 'modify' :
        modifyTopping();
        break;

    case 'delete' :
        deleteTopping();
        break;


    default :
        // if action is not defined or unknown
        // move to main Topping page
        header('Location: index.php');
}



function addTopping()
{
        $name = $_POST['txtName'];
        $email = $_POST['txtEmail'];
        $phone = $_POST['txtPhone'];
        $address = $_POST['txtAddress'];
        $cuisine = $_POST['txtCuisine'];
        $mini_order = $_POST['txtMini_order'];
                $suburbs = $_POST['txtSuburbs'];
        $menu = $_POST['txtMenu'];
        $reviews = $_POST['txtReviews'];
        $logo = $_POST['txtLogo'];
        $takeaway_hours = $_POST['txtTakeawayHours'];
        $delivery_hours = $_POST['txtDeliveryHours'];
        $map = $_POST['txtMap'];
                $promotions = $_POST['txtPromotions'];

        $sql   = "INSERT INTO restaurant_info(name, email, phone, address, cuisine, mini_order, suburbs, menu, reviews, logo, takeaway_hours, delivery_hours, map, promotions)
        VALUES ('$name','$email','$phone','$address','$cuisine','$mini_order','$suburbs','$menu','$reviews','$logo','$takeaway_hours','$delivery_hours','$map','$promotions')";     
        dbQuery($sql);
        header('Location: index.php');  

}

    //image
    $uploadDir = '../../images/';
    for($i=0;$i<count($_FILES["fleImage"]["name"]);$i++)
    {
    if($_FILES["fleImage"]["tmp_name"][$i] != '')
    {
        $image = $_FILES["fleImage"];
        if (trim($image['tmp_name'][$i]) != '') {
        $ext = substr(strrchr($image['name'][$i], "."), 1); //$extensions[$image['type']];

        // generate a random new file name to avoid name conflict
        $imagePath = md5(rand() * time()) . ".$ext";

        list($width, $height, $type, $attr) = getimagesize($image['tmp_name'][$i]); 

        // make sure the image width does not exceed the
        // maximum allowed width
        if (LIMIT_PRODUCT_WIDTH && $width > MAX_PRODUCT_IMAGE_WIDTH) {
            $result    = createThumbnail($image['tmp_name'][$i], $uploadDir . $imagePath, MAX_PRODUCT_IMAGE_WIDTH);
            $imagePath = $result;
        } else {
            $result = move_uploaded_file($image['tmp_name'][$i], $uploadDir . $imagePath);
        }   

        if ($result) {
            // create thumbnail
            $thumbnailPath =  md5(rand() * time()) . ".$ext";
            $result = createFixThumbnail($uploadDir . $imagePath, $uploadDir . $thumbnailPath, THUMBNAIL_WIDTH,THUMBNAIL_HEIGHT);

            // create thumbnail failed, delete the image
            if (!$result) {
                unlink($uploadDir . $imagePath);
                $imagePath = $thumbnailPath = '';
            } else {
                $thumbnailPath = $result;
            }   
        } else {
            // the product cannot be upload / resized
            $imagePath = $thumbnailPath = '';
        }


    }

        mysql_query("INSERT INTO restaurant_info(Rest_Logo)
        VALUES ('$Rest_Logo')"; 
    }   
    }




/*
    Modify a Topping
*/
function modifyTopping()
{
    $toppingId   = (int)$_POST['hidToppingId']; 
    $name = $_POST['txtName'];
    $email = $_POST['txtEmail'];
    $phone = $_POST['txtPhone'];
    $address = $_POST['txtAddress'];
    $cuisine = $_POST['txtCuisine'];
    $mini_order = $_POST['txtMini_order'];
        $suburbs = $_POST['txtSuburbs'];
    $menu = $_POST['txtMenu'];
    $reviews = $_POST['txtReviews'];
    $logo = $_POST['txtLogo'];
    $takeaway_hours = $_POST['txtTakeawayHours'];
    $delivery_hours = $_POST['txtDeliveryHours'];
    $map = $_POST['txtMap'];
        $promotions = $_POST['txtPromotions'];
    $sql   = "UPDATE restaurant_info 
              SET  name='$name',  email='$email',  phone='$phone',  address='$address',  cuisine='$cuisine',  mini_order='$mini_order',  suburbs='$suburbs', menu='$menu',  reviews='$reviews',  logo='$logo',  takeaway_hours='$takeaway_hours',  delivery_hours='$delivery_hours',  map='$map',  promotions='$promotions'
              WHERE rest_id = $toppingId";
    dbQuery($sql);
    header('Location: index.php');  

}

/*
    Remove a topping
*/
function deleteTopping()
{
    if (isset($_GET['toppingId']) && (int)$_GET['toppingId'] > 0) {
        $toppingId = (int)$_GET['toppingId'];
    } else {
        header('Location: index.php');
    }


    $sql = "DELETE FROM restaurant_info 
            WHERE rest_id = $toppingId";
    dbQuery($sql);

    header('Location: index.php');
}
?>

2 个答案:

答案 0 :(得分:0)

要将文件保存在数据库中,您需要获取文件和文件的内容。将其保存在DB中。您应该选择数据类型为longblob

这可以帮助您:http://forums.mysql.com/read.php?20,17671,27914

答案 1 :(得分:0)

我刚修好它,我不得不对sql代码做一些修改。

<?php
require_once '../../library/config.php';
require_once '../library/functions.php';
error_reporting(E_ALL);
checkUser();

$action = isset($_GET['action']) ? $_GET['action'] : '';

switch ($action) {

    case 'add' :
        addTopping();
        break;

    case 'modify' :
        modifyTopping();
        break;

    case 'delete' :
        deleteTopping();
        break;


    default :
        // if action is not defined or unknown
        // move to main Topping page
        header('Location: index.php');
}














function addTopping()
{
    if($_FILES['bgImg']['tmp_name']!='')
    {
        $srcFile = $_FILES['bgImg']['tmp_name'];
        $size       = $_FILES['bgImg']['size'];
        if($size<5227520) //if file is less than 5MB
        {
            $ext = substr(strrchr($_FILES['bgImg']['name'], "."), 1); 
            $ext = strtolower($ext);
            if (($ext != "jpg") && ($ext != "jpeg") && ($ext != "png") && ($ext != "gif")) 
            {
            //print error message
            print "<script>alert('Unknown File Format Detected')</script>";
            print "<script>window.location='index.php'</script>";
            exit;
            }
            else
            {
            $img_name = md5(rand() * time()) . ".$ext";

            $dest = '../../testingImageIntoFolderAndDatabase/upload/';
        $name = $_POST['txtName'];
        $email = $_POST['txtEmail'];
        $phone = $_POST['txtPhone'];
        $address = $_POST['txtAddress'];
        $cuisine = $_POST['txtCuisine'];
        $mini_order = $_POST['txtMini_order'];
                $suburbs = $_POST['txtSuburbs'];
        $menu = $_POST['txtMenu'];
        $reviews = $_POST['txtReviews'];
        $logo = $_POST['txtLogo'];
        $takeaway_hours = $_POST['txtTakeawayHours'];
        $delivery_hours = $_POST['txtDeliveryHours'];
        $map = $_POST['txtMap'];
                $promotions = $_POST['txtPromotions'];


            //copy new image
            move_uploaded_file($_FILES['bgImg']['tmp_name'],$dest.$img_name);
            dbQuery("insert into restaurant_info set Rest_Logo='$img_name', name='$name', email='$email', phone='$phone', address='$address', cuisine='$cuisine', mini_order='$mini_order', suburbs='$suburbs', menu='$menu', reviews='$reviews', logo='$logo', takeaway_hours='$takeaway_hours', delivery_hours='$delivery_hours', map='$map', promotions='$promotions'");

            print "<script>window.location='index.php'</script>";
            exit;           
            }
        }
        else
        {
                print "<script>alert('File Size Exceeded!')</script>";
                print "<script>window.location='index.php'</script>";
                exit;
        }
    }


}











/*
    Modify a Topping
*/
function modifyTopping()
{
    $toppingId   = (int)$_POST['hidToppingId']; 
    $name = $_POST['txtName'];
    $email = $_POST['txtEmail'];
    $phone = $_POST['txtPhone'];
    $address = $_POST['txtAddress'];
    $cuisine = $_POST['txtCuisine'];
    $mini_order = $_POST['txtMini_order'];
        $suburbs = $_POST['txtSuburbs'];
    $menu = $_POST['txtMenu'];
    $reviews = $_POST['txtReviews'];
    $logo = $_POST['txtLogo'];
    $takeaway_hours = $_POST['txtTakeawayHours'];
    $delivery_hours = $_POST['txtDeliveryHours'];
    $map = $_POST['txtMap'];
        $promotions = $_POST['txtPromotions'];
    $sql   = "UPDATE restaurant_info 
              SET  name='$name',  email='$email',  phone='$phone',  address='$address',  cuisine='$cuisine',  mini_order='$mini_order',  suburbs='$suburbs', menu='$menu',  reviews='$reviews',  logo='$logo',  takeaway_hours='$takeaway_hours',  delivery_hours='$delivery_hours',  map='$map',  promotions='$promotions'
              WHERE rest_id = $toppingId";
    dbQuery($sql);
    header('Location: index.php');  

}

/*
    Remove a topping
*/
function deleteTopping()
{
    if (isset($_GET['toppingId']) && (int)$_GET['toppingId'] > 0) {
        $toppingId = (int)$_GET['toppingId'];
    } else {
        header('Location: index.php');
    }


    $sql = "DELETE FROM restaurant_info 
            WHERE rest_id = $toppingId";
    dbQuery($sql);

    header('Location: index.php');
}
?>