我想使用php将我的图像(多个)存储到mysql数据库中

时间:2013-06-13 07:59:29

标签: php mysql

我有一个用PHP编写的表单。用户填写的表单数据直接保存到MySQL数据库中,但图像和下拉选项除外。

我的问题是:

  1. 将图像或其路径保存到数据库中
  2. 检索这些图片
  3. 将下拉选项保存到数据库中
  4. The form looks like this

    这是表单的HTML代码:(form.html)

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <title>Untitled Document</title>
            <script type="text/javascript">
                var categories = [];
                categories["startList"] = ["Rental","Sale"]
                categories["Rental"] = ["Residential","Commercial"];
                categories["Sale"] = ["Commercial","Residential"];
                categories["Residential"] = ["Flot","Independent"];
                categories["Commercial"] = ["Play & Plug","Baseshare"];
                categories["Biography"] = ["Play & Plug","Bareshare"];
                categories["Fiction"] = ["Flot","Independent"];
                var nLists = 3; // number of select lists in the set
    
                function fillSelect(currCat, currList) {
                    var step = Number(currList.name.replace(/\D/g,""));
                    for (i = step; i < nLists+1; i++) {
                        document.forms['tripleplay']['List'+i].length = 1;
                        document.forms['tripleplay']['List'+i].selectedIndex = 0;
                    }
                    var nCat = categories[currCat];
                    for (each in nCat) {
                        var nOption = document.createElement('option'); 
                        var nData = document.createTextNode(nCat[each]); 
                        nOption.setAttribute('value',nCat[each]); 
                        nOption.appendChild(nData); 
                        currList.appendChild(nOption); 
                    } 
                }
    
                function init() {
                    fillSelect('startList',document.forms['tripleplay']['List1'])
                }
    
                navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);
            </script> 
        </head>
        <body>
        <table width="60%">
            <form action="process.php" method="post" enctype="multipart/form-data" name="tripleplay">
            <tr>
                <td width="44%">Full Name : </td>
                <td width="56%"><input size="25" type="text" name="fullname" id="fullname" /></td>
            </tr>
            <tr>
                <td valign="top">Rental Type:</td>
                <td>
                    <select name = 'List1' onchange = "fillSelect(this.value,this.form['List2'])">
                        <option selected>Make a Selection</option>
                    </select>
                    <br /><br />
                    <select name = 'List2' onchange = "fillSelect(this.value,this.form['List3'])">
                        <option selected>Make a Selection</option>
                    </select>
                    <br /><br />
                    <select name = 'List3' onchange = "getValue(this.value, this.form['List2'].value, this.form['List1'].value)">
                        <option selected >Make a Selection</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>Area : </td>
                <td><input size="25" type="text" name="area" id="area" /> sq.ft.</td>
            </tr>
            <tr>
                <td>Owner Mobile / Landline</td>
                <td><input size="25" type="text" name="ownermobile" id="ownermobile" /></td>
            </tr>
            <tr>
                <td><p>E-mail</p></td>
                <td><input size="25" type="text" name="email" id="email" /></td>
            </tr>
            <tr>
                <td valign="top">Pictures of Property</td>
                <td>
    
                    <input type="file" name="image_one" id="image_one" />
                    <input type="file" name="image_two" id="image_two" />
                    <input type="file" name="image_three" id="image_three" />
                </td>
            </tr>
            <tr>
                <td valign="top">Other details you would like to share about your property:</td>
                <td>
                    <textarea size="25" name="otherdetail" id="otherdetail" cols="45" rows="5">
                    </textarea>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="submit" name="submit" id="submit" value="Submit" /></td>
            </tr>
        </form>
    </table>
    </body>
    </html>
    

    我的流程表格看起来像这样(process.php)

    <?
    if( $_POST )
    {
      $con = mysql_connect("","","");
    
      if (!$con)
      {
        die('Could not connect: ' . mysql_error());
      }
    
      mysql_select_db("", $con);
    
      $users_fullname = $_POST['fullname'];
      $users_area = $_POST['area'];
      $users_ownermobile = $_POST['ownermobile'];
      $users_email = $_POST['email'];
      $users_image_one = $_POST['image_one'];
      $users_image_two = $_POST['image_two'];
      $users_image_three = $_POST['image_three'];
      $users_otherdetail = $_POST['otherdetail'];
    
      $users_fullname = htmlspecialchars($users_fullname);
      $users_area = htmlspecialchars($users_area);
      $users_ownermobile = htmlspecialchars($users_ownermobile);
      $users_email = htmlspecialchars($users_email);
      $users_image_one = htmlspecialchars($users_image_one);
      $users_image_two = htmlspecialchars($users_image_two);
      $users_image_three = htmlspecialchars($users_image_three);
      $users_otherdetail = htmlspecialchars($users_otherdetail);
    
      $query = "
      INSERT INTO `vkrental`.`Owner_detail` (
    
    `fullname` ,
    `area` ,
    `ownermobile` ,
    `email` ,
    `image_one` ,
    `image_two` ,
    `image_three` ,
    `otherdetail`
    )
    VALUES ( '$users_fullname',
        '$users_area',  '$users_ownermobile', '$users_email', '$users_image_one','$users_image_two','$users_image_three', '$users_otherdetail'
        );";
    
      mysql_query($query);
    
      echo "<h2>some text.</h2>";
    
      mysql_close($con);
    }
    ?>
    

    和mysql数据库表看起来像这样

    CREATE TABLE `Owner_detail` (
      `id` int(10) NOT NULL auto_increment,
      `fullname` varchar(30) NOT NULL,
      `area` varchar(30) NOT NULL,
      `ownermobile` varchar(20) NOT NULL,
      `email` varchar(20) NOT NULL,
      `image_one` blob NOT NULL,
      `image_two` blob NOT NULL,
      `image_three` blob NOT NULL,
      `otherdetail` varchar(300) NOT NULL,
      PRIMARY KEY  (`id`)
    );
    

    请帮帮我。

2 个答案:

答案 0 :(得分:2)

我强烈建议您不要将图像保存在MySQL数据库中。相反,我建议您将图像上传到服务器或使用Amazon S3 / RackSpace Cloud Files等服务,然后将链接存储到数据库中的特定图像。

像Facebook / Twitter /等大型网站不会在数据库中存储图像。当不需要时,它会向DB添加不必要的工作量。

您可以使用以下内容上传图像并将其保存到MySQL中:

require_once('amazon-web-services-api/sdk.class.php');

$AWS_KEY        = 'KEY';
$AWS_SECRET_KEY = 'SECRET';

$s3 = new AmazonS3(array(
    "key"    => $AWS_KEY,
    "secret" => $AWS_SECRET_KEY
));

$s3 -> set_region('s3-eu-west-1.amazonaws.com');

$bucket   = 'bucket_name';
$filename = 'picture.jpeg';

$response = $s3 -> create_object($bucket, $filename, array( 
                                'fileUpload' => $_FILES['photo']['tmp_name'],
                                'acl' => $s3::ACL_PUBLIC
                                ));

if($response -> status == 200){
    // The file was Uploaded and Saved to S3 OK!!
    $file_location = 'https://s3-eu-west-1.amazonaws.com/'.$bucket.'/'.$filename;

    $query = "INSERT INTO tablename (id, image_url) VALUES ($ID_NUMBER, '$file_location')";
    $result= $mysqli -> query($query);
    $num   = $mysqli -> affected_rows;

    if($num == 1){
        // The data was saved OK - redirect or say thanks, whatever you want.
    }else{
        // Display an error, log an error, do whatever is necessary 
    }

}

要检索数据,您只需编写SELECT语句即可获取数据。然后,您的表中将包含一个包含图像URL的列。然后,您可以将图片网址放入<img src="LOCATION" />标记以显示

答案 1 :(得分:0)

你会像其他一切一样保存它们。 当您将类别添加到数据库并获取它们以生成下拉列表时,您可以引用该ID,否则您应该保存选项值本身并尝试在生成下拉列表时将存储的选项与现有类别进行匹配。 / p>

您应该像这样更改数据库结构:

CREATE TABLE `Owner_detail` (
  `id` int(10) NOT NULL auto_increment,
  `fullname` varchar(30) NOT NULL,
  `area` varchar(30) NOT NULL,
  `ownermobile` varchar(20) NOT NULL,
  `email` varchar(20) NOT NULL,
  `otherdetail` varchar(300) NOT NULL,
  PRIMARY KEY  (`id`)
);

CREATE TABLE `image` (
  `id` int(10) NOT NULL auto_increment,
  `owner_id int NOT NULL,
  `path` varchar(255) NOT NULL,
  `title` varchar(100) NOT NULL,
  PRIMARY KEY  (`id`),
  INDEX `fk_owner_has_image_idx` (`owner_id` ASC) ,
  CONSTRAINT `fk_owner_has_image`
   FOREIGN KEY (`owner_id` )
   REFERENCES `Owner_detail` (`id` )
   ON DELETE CASCADE
   ON UPDATE CASCADE)
);

因此,您可以根据需要为每个用户保存尽可能多的图像。如果您按照自己的方式进行操作,则每个用户只能使用三张图片。 当您想要移动类别时,您可以将cols添加到Owner_detail表中,您可以在其中引用所选类别/下拉选项。