2011-12-07 43 views
0

我正在建立一個小型的ajax聊天網站,並且正在添加一個圖像上傳功能,內置PHP,MySQL和jquery的Ajax功能。我的代碼目前可以讓你上傳消息,我可以準備上傳圖像並存儲數據庫的URL。在PHP Global或函數中傳遞一個變量?

但我需要將該變量傳遞給另一個if語句,以檢查用戶提交消息的時間。 我似乎無法跨越並進入我的數據庫。

嘗試全局var,其他的東西 - 認爲必須缺少的東西。這可能是很明顯的,請原諒代碼我是一個平面設計師學習代碼!

$imageurl = ""; 


if (isset($_FILES["file"])) { 

    //properties of uploaded file 
    $name = $_FILES["file"] ["name"]; 
    $type = $_FILES["file"] ["type"]; 
    $size = $_FILES["file"] ["size"]; 
    $temp = $_FILES["file"] ["tmp_name"]; 
    $error = $_FILES["file"] ["error"]; 


    if ($error > 0) { 
     die("Error uploaded file!"); 
    } 
    else 
    { 

     if ($type == "video/avi" || $size > 2000000) { 
      ?> 
     <br> 
     <p><?die("format is not allowed or size too big!");?></p> 

     <? 
     } 
     else 
     { 
      move_uploaded_file($temp, "msg_image/" . $name); 
     } 

    } 
    //store url for insertation 
    $imageurl = "msg_image/" . $name; 

    echo '<p>You added a ' . $name . ' to your message</p>'; 

    return $imageurl; 


} 


/////need the var in here to store and update mysql database 
if (isset($_POST['message'])) { 

    $tostore = $imageurl; 
    $username = protect($_POST['username']); 
    $message = protect($_POST['message']); 
    $time = time(); 

    $sql = "INSERT INTO messages 
     (username, msgcontent, imageurl, msgtime) 
     VALUES ('$username', '$message', '$tostore', $time)"; 


    $result = mysql_query($sql); 


} 
+3

我重新格式化您的文章是爲了便於閱讀。下次請自行檢查。 – Bart

+2

這是一個函數嗎?嘗試忽略'return $ imageurl;'部分。我猜測第二個「if」檢查從未達到。順便說一下:你允許用戶覆蓋對方的文件:如果兩個用戶都使用「img.jpg」,那麼只有最後一個用戶會保持你的方式。另外,您只會將視頻文件標記爲不需要。你最好指定你實際想要的類型*允許*而不是其他方式(比如現在)。 – Bart

回答

3

你的 「迴歸$ IMAGEURL」 語句被過早地停止腳本。

http://php.net/manual/en/function.return.php

echo "hello"; 

return "world"; 

echo "!"; 

只會返回

hello 
+0

是的,返回$ imageurl;線阻止它通過。如果您計劃不將它保存到數據庫,OP應該只會返回。 – Nthalk

+0

感謝球員們將採取評論和答案!我在你的債務,有一天我會發布我自己的答案,我希望! – ChrisSherwood

+0

嘿傢伙刪除了返回$ imageurl和我的腳本仍然沒有插入到MySQL數據庫。奇怪!我可以重做我想要的代碼,並在消息等的同時上傳圖片等。當簡單的東西無法正常工作時,它只是讓我感到毛骨悚然!問題必須與我的MySQL插入數據庫。 – ChrisSherwood

相關問題