dongqian9567
dongqian9567
2013-09-18 10:42

图像更新php mysql

已采纳

I have a problem with updating images. Sending images to the server and insert new records runs without a problem but have not edited when editing photos, and data to the database are thrown only texts and records not responsible for the pictures. Thank you in advance for your help

Form

<?php
//1. polaczenie z baza danych
//polaczenie z baza danych + ustawienie kodowania na utf8
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "3edcvfr4";
$dbname = "dw_bookstore";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

//sprawdzenie polaczenia
if (mysqli_connect_errno()) {
    printf("Connect failed: %s
", mysqli_connect_error());
    exit();
}

//zmaiana znako na utf8
if (!mysqli_set_charset($connection, "utf8")) {
    printf("Error loading character set utf8: %s
", mysqli_error($connection));
} else {
    printf("Kodowanie ustawione na: %s
", mysqli_character_set_name($connection));
}
?>

<?php
    // get ID
    @$id = $_GET['id'];

    @$query  = "SELECT * FROM photographs WHERE id = '$id' ";
    //pokazuje co zostalo zmienione
    echo $query;

    $result = mysqli_query($connection, $query);
    if (!$result) {
        die("zapytanie sie nie powiodlo");
    }
    $row = mysqli_fetch_array($result);

?>


<?php
//if (!id) {
//  redirect_to("costam.php");
//  }
?>

<!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>Update Form</title>
</head>
<body>
        <form action="database_update_action.php" method="post" enctype="multipart/form-data" name="form1" target="_blank">
      <table border="0" cellspacing="2" cellpadding="2">
        <tr>
          <td>ID:</td>
          <td><input name="id" type="text" id="id" value="<?php echo $row['id'];?>"></td>
        </tr>
        <tr>
          <td>filename</td>
          <td><label for="filename"></label>
          <input name="filename" type="file" id="filename" value="<?php echo $row['filename'];?>"></td>
        </tr>
        <tr>
          <td>type</td>
          <td><label for="type"></label>
          <input name="type" type="text" id="type" value="<?php echo $row['type'];?>"></td>
        </tr>
        <tr>
          <td>size</td>
          <td><label for="size"></label>
          <input name="size" type="text" id="size" value="<?php echo $row['size'];?>"></td>
        </tr>
        <tr>
          <td>caption</td>
          <td><label for="caption"></label>
          <input name="caption" type="text" id="caption" value="<?php echo $row['caption'];?>"></td>
        </tr>
        <tr>
          <td>caption_2</td>
          <td><label for="caption_2"></label>
          <input name="caption_2" type="text" id="caption_2" value="<?php echo $row['caption_2'];?>"></td>
        </tr>
        <tr>
          <td>txt</td>
          <td><label for="txt"></label>
          <textarea name="txt" id="txt" cols="45" rows="5"><?php echo $row['txt']; ?></textarea></td>
        </tr>
        <tr>
          <td>&nbsp;</td>
          <td><input type="submit" name="submit" id="submit" value="update"></td>
        </tr>
      </table>
    </form>

<?php
    //4. release returned data
    //mysqli_free_result($result);
?>
</body>
</html>

<?php
    // 5. Zamkniecie bazy
    mysqli_close($connection);
?>

Action

<?php
//1. polaczenie z baza danych
//polaczenie z baza danych + ustawienie kodowania na utf8
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "3edcvfr4";
$dbname = "dw_bookstore";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

//sprawdzenie polaczenia
if (mysqli_connect_errno()) {
    printf("Connect failed: %s
", mysqli_connect_error());
    exit();
}

//zmaiana znako na utf8
if (!mysqli_set_charset($connection, "utf8")) {
    printf("Error loading character set utf8: %s
", mysqli_error($connection));
} else {
    printf("Kodowanie ustawione na: %s
", mysqli_character_set_name($connection));
}
?>

<?php
//2. przeslanie zdjecia wraz z danymi


    @$path = $_FILES["file"]["name"];
    @$type = $_FILES["file"]["type"];
    @$size = $_FILES["file"]["size"];
    $id = $_POST["id"];
    $caption = $_POST["caption"];
    $caption_2 = $_POST["caption_2"];
    $txt = $_POST["txt"];

    // przyklad - by moc wpisac 'costam' - tylko txt, nie "file" i "int"
    $caption = mysqli_real_escape_string($connection, $caption);
    $caption_2 = mysqli_real_escape_string($connection, $caption_2);
    $txt = mysqli_real_escape_string($connection, $txt);

    // 2. Perform database query
    $query  = "UPDATE photographs SET ";
    $query .= "id = '{$id}', ";
    $query .= "filename = '{$path}', ";
    $query .= "size = '{$size}', ";
    $query .= "type = '{$type}', ";
    $query .= "caption = '{$caption}', ";
    $query .= "caption_2 = '{$caption_2}', ";
    $query .= "txt = '{$txt}' ";
    $query .= "WHERE id = {$id}";
    echo $query;

    //$query  = "INSERT INTO photographs (";
    //$query .= "  filename, type, size, caption, caption_2, txt";
    //$query .= ") VALUES (";
    //$query .= "  '{$path}', '{$type}', '{$size}', '{$caption}', '{$caption_2}', '{$txt}'";
    //$query .= ")";

    $result = mysqli_query($connection, $query);
    if ($result) {
        // Success
        // redirect_to("somepage.php");
        echo " Sukces! Dane zostaly przeslane na serwer. ";
    } else {
        // Failure
        // $message = "Subject creation failed";
        die("Przeslanie danych nie powiodlo sie. " . mysqli_error($connection));


        if(isset($_POST['submit'])){
    if (((@$_FILES["file"]["type"] == "image/gif")
    || (@$_FILES["file"]["type"] == "image/jpeg")
    || (@$_FILES["file"]["type"] == "image/JPEG")
    || (@$_FILES["file"]["type"] == "image/jpg")
    || (@$_FILES["file"]["type"] == "image/png")
    || (@$_FILES["file"]["type"] == "image/pjpeg"))
    && (@$_FILES["file"]["size"] < 600000))
    {
        if ($_FILES["file"]["error"] > 0)
        {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
        }
        else
        {
        if (file_exists("../images/" . $_FILES["file"]["name"])){
                echo $_FILES["file"]["name"] . " to zdjecie juz istnieje. ";
        }
        else{
        move_uploaded_file($_FILES["file"]["tmp_name"], "../images/" .              $_FILES["file"]["name"]);


                echo " Przeslane do katalogu : " . "images/" . $_FILES["file"]["name"];



      }
     }
    }
   }
}


?>

<!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>Update Action</title>
</head>
<body>
</body>
</html>
<?php
  // 5. Zamkniecie polaczenia
  mysqli_close($connection);
?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • doukai2839 doukai2839 8年前

    When you are updating, you are not providing the image file again so it updates it with null value when you want to update. This is probably occuring when you don't select an image file. You can replace the query section like this:

    $query  = "UPDATE photographs SET ";
        $query .= "id = '{$id}', ";
    
    if(isset($_FILES['file'])){
        $query .= "filename = '{$path}', ";
        $query .= "size = '{$size}', ";
        $query .= "type = '{$type}', ";
    }
    
        $query .= "caption = '{$caption}', ";
        $query .= "caption_2 = '{$caption_2}', ";
        $query .= "txt = '{$txt}' ";
        $query .= "WHERE id = {$id}";
        echo $query;
    

    EDIT Another thing, you should escape the value of file so add this line before creation sql query:

     $path = mysql_real_escape_string($path);
    
    点赞 评论 复制链接分享
  • dounie0889 dounie0889 8年前

    "Now, i can update BUT must select image. If I'm not selecting an image, my image field in database will be empty but other data updates are OK."

    I think it works ok now

    $query  = "UPDATE photographs SET ";
                $query .= "id = '{$id}', ";
    
        if(!empty($_FILES['filename']['name'])){
    
                $query .= "filename = '{$path}', ";
                $query .= "size = '{$size}', ";
                $query .= "type = '{$type}', ";
            }
                $query .= "caption = '{$caption}', ";
                $query .= "caption_2 = '{$caption_2}', ";
                $query .= "txt = '{$txt}' ";
                $query .= "WHERE id = {$id}";
    
    点赞 评论 复制链接分享
  • doudong3570 doudong3570 8年前

    I think I did here is good code, Now, i can update BUT must select image. If I'm not selecting an image, my image field in database will be empty but other data updates are OK..

    <?php
    //1. polaczenie z baza danych
    //polaczenie z baza danych + ustawienie kodowania na utf8
    $dbhost = "localhost";
    $dbuser = "root";
    $dbpass = "3edcvfr4";
    $dbname = "dw_bookstore";
    $connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
    
    //sprawdzenie polaczenia
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s
    ", mysqli_connect_error());
        exit();
    }
    
    //zmaiana znako na utf8
    if (!mysqli_set_charset($connection, "utf8")) {
        printf("Error loading character set utf8: %s
    ", mysqli_error($connection));
    } else {
        printf("Kodowanie ustawione na: %s
    ", mysqli_character_set_name($connection));
    }
    ?>
    
    
    <?php
        // get ID
        //@$id = $_GET['id'];
    
        if(isset($_POST['id'])){
        $id=$_POST['id'];
        }else{
        $id=$_GET['id'];
        }
    
        //$id = (int) $_GET['id'];
        //if(!$id) {
        //die('Brak indentyfikatora');
        //}
    
        @$query  = "SELECT * FROM photographs WHERE id = '$id' ";
        //pokazuje co zostalo zmienione
        echo $query;
    
        $result = mysqli_query($connection, $query);
        if (!$result) {
            die("zapytanie sie nie powiodlo");
        }
        $row = mysqli_fetch_array($result);
    
    ?>
    
    
    
    <pre>
    <?php
    print_r($_POST);
    ?>
    </pre>
    <br />
    
    <?php # Upload image
    
    // sprawdzanie czy formularz został przesłany.
    if (isset($_POST['submitted'])) {
    
        // czy użytkownik wybrał plik.
        //if (isset($_FILES['upload'])) {
        if (isset($_FILES['filename'])) {
    
            // sprawdzanie czy przesylany plik jest wlasciwego typu. Powinien byc albo jpg albo png
            $allowed = array ('image/pjpeg', 'image/jpeg', 'image/JPEG', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/x-png');
            if (in_array($_FILES['filename']['type'], $allowed)) {
    
                // skopiowanie pliku do katalogu na serwerze.
                if (move_uploaded_file ($_FILES['filename']['tmp_name'], "../images/{$_FILES['filename']['name']}")) {
                    echo '<p><em>Sukces, plik zostal przeslany!</em></p>';
                } // koniec move... IF.
    
            } else { // zly typ pliku.
                echo '<p class="error">Prosze wybrac jpg albo png.</p>';
            }
    
        } // Koniec isset($_FILES['upload']) IF.
    
    
        @$path = $_FILES["filename"]["name"];
        @$type = $_FILES["filename"]["type"];
        @$size = $_FILES["filename"]["size"];
        @$caption = $_POST["caption"];
        @$caption_2 = $_POST["caption_2"];
        @$txt = $_POST["txt"];
    
        // przyklad - by moc wpisac 'costam' - tylko txt, nie "file" i "int"
        $caption = mysqli_real_escape_string($connection, $caption);
        $caption_2 = mysqli_real_escape_string($connection, $caption_2);
        $txt = mysqli_real_escape_string($connection, $txt);
    
       $query  = "UPDATE photographs SET ";
            $query .= "id = '{$id}', ";
    
        if(isset($_FILES['filename'])){
            $query .= "filename = '{$path}', ";
            $query .= "size = '{$size}', ";
            $query .= "type = '{$type}', ";
        }
    
            $query .= "caption = '{$caption}', ";
            $query .= "caption_2 = '{$caption_2}', ";
            $query .= "txt = '{$txt}' ";
            $query .= "WHERE id = {$id}";
    
        echo $query;
    
        $result = mysqli_query($connection, $query);
        if ($result) {
            // Success
            // redirect_to("somepage.php");
            echo " Sukces! Dane zostaly przeslane na serwer. ";
        } else {
            // Failure
            // $message = "Subject creation failed";
            die("Przeslanie danych nie powiodlo sie. " . mysqli_error($connection));
    
        // Check for an error:
    
        if ($_FILES['filename']['error'] > 0) {
            echo '<p class="error">The file could not be uploaded because: <strong>';
    
            // Print a message based upon the error.
            switch ($_FILES['filename']['error']) {
                case 1:
                    print 'The file exceeds the upload_max_filesize setting in php.ini.';
                    break;
                case 2:
                    print 'The file exceeds the MAX_FILE_SIZE setting in the HTML form.';
                    break;
                case 3:
                    print 'The file was only partially uploaded.';
                    break;
                case 4:
                    print 'No file was uploaded.';
                    break;
                case 6:
                    print 'No temporary folder was available.';
                    break;
                case 7:
                    print 'Unable to write to the disk.';
                    break;
                case 8:
                    print 'File upload stopped.';
                    break;
                default:
                    print 'A system error occurred.';
                    break;
            } // End of switch.
    
            print '</strong></p>';
    
        } // End of error IF.
    
        // Usuniecie zdjecia z folderu tymczasowego:
        if (file_exists ($_FILES['filename']['tmp_name']) && is_file($_FILES['filename']['tmp_name']) ) {
            unlink ($_FILES['filename']['tmp_name']);
        }
    
    } // End of the submitted conditional.
    
    }
    
    ?>
    
    
    <!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>Update Action</title>
    </head>
    <body>
    <form enctype="multipart/form-data" action="database_update.php" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="524288">
    <legend>Wybierz JPEG albo PNG. Plik nie może przekraczać 512KB:</legend>
          <table border="0" cellspacing="2" cellpadding="2">
            <tr>
              <td>ID:</td>
              <td><input name="id" type="hidden" id="id" value="<?php echo $row['id'];?>"></td>
            </tr>
            <tr>
              <td>filename</td>
              <td><label for="filename"></label>
              <input name="filename" type="file" id="filename" value="<?php echo $row['filename'];?>"></td>
            </tr>
            <tr>
              <td>caption</td>
              <td><label for="caption"></label>
              <input name="caption" type="text" id="caption" value="<?php echo $row['caption'];?>"></td>
            </tr>
            <tr>
              <td>caption_2</td>
              <td><label for="caption_2"></label>
              <input name="caption_2" type="text" id="caption_2" value="<?php echo $row['caption_2'];?>"></td>
            </tr>
            <tr>
              <td>txt</td>
              <td><label for="txt"></label>
              <textarea name="txt" id="txt" cols="45" rows="5"><?php echo $row['txt']; ?></textarea></td>
            </tr>
            <tr>
              <td>&nbsp;</td>
              <td><input type="submit" name="submit" value="Submit" />
                <input type="hidden" name="submitted" value="TRUE" />
          </td>
            </tr>
          </table>
        </form>
    </body>
    </html>
    <?php
      // 5. Zamkniecie polaczenia
      mysqli_close($connection);
    ?>
    
    点赞 评论 复制链接分享