使用php将图片更新到数据库表中

时间:2015-02-12 18:45:39

标签: php mysqli

我有一个地址表,其中一个字段是图像blob。当我通过$ POST更新记录并包含图像时,一切正常。但是,如果$ POST中没有包含图像,我想重用已存储在记录中的图像。这是我遇到的问题。当我运行下面的代码时,它不会更新图像文件。这是我的代码。

function UpdateRecordfromPost()
{
 if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
    $FirstName =  test_input($_POST['fname']);
    $LastName =  test_input($_POST['lname']);
    $Address =  test_input($_POST['address']);
    $Town =  test_input($_POST['town']);
    $Postcode = test_input($_POST['pcode']);
    $Phone = test_input($_POST['phone']);
    $Email =  test_input($_POST['email']);
    $ID = ($_POST['idname']);
    }
    $mysqli = new mysqli( $GLOBALS['servername'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['dbname']);   
        if ($mysqli->connect_error) 
            {
                die("Connection failed: " . $mysqli->connect_error);
            }
    $image = GetimagefromPost();  //this function returns a image and seems to work
    if ($image == "")
    {
        $image = Saveimaqgefile($ID);
    }
    $query = "UPDATE addressbook SET    firstname='$FirstName',lastname='$LastName',street='$Address',town='$Town',PostCode='$Postcode',phone='$Phone',email='$Email',Photo='$image' WHERE id='$ID'";
        if ($result = $mysqli->query($query))
           {
           echo "Updated record successfully";
           } 
        else 
            {
               echo "Error: " . $query . "<br>" . $mysqli->error;
            }
 $mysqli->close();
 }

function Saveimaqgefile($file_id) {
    $mysqli = new mysqli( $GLOBALS['servername'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['dbname']);   
if ($mysqli->connect_error) 
    {
        die("Connection failed: " . $conn->connect_error);
    }
    $sql= "SELECT * from ".$GLOBALS['dbname']. " WHERE id=".$file_id;
    $result = $mysqli->query($sql);
    if ($result->num_rows > 0) 
    {
        $row=mysqli_fetch_array($result);

    } 
    else { $row = "";}

      $mysqli->close();


    return base64_encode($row['Photo']);
}

这是我的第一个问题,对不起,如果我做错了

1 个答案:

答案 0 :(得分:0)

您需要条件逻辑。

if (image was uploaded) {
    mysqli_query('... update record with new image ...;);
} else {
    mysqli_query('... update record WITHOUT image data ...');
}

对于大多数其他类型的(小)数据,您可以在单个查询中执行此操作,例如

UPDATE ... SET field=IF($newdata = '', field, $newdata)

但是您的图片blob可能很大,而且您不想在同一个查询字符串中重复两次。