2012-03-11 4 views
0

syste 파일을 통해 이미지 파일을 업로드하고 sql 데이터베이스에 경로를 저장하는 방법에 대한 독학 자습서가 없습니다. 일부 사이트에서는 언급했지만 제대로 설명하지 않았습니다. Nyway PHP를 통해 이미지를 업로드하고 있으며 업로드 된 이미지의 경로를 SQL 데이터베이스에 저장하려고합니다. 나는이 페이지가 절대적으로 잘 작동하지만 문제는 다음 파일에 문제Sql 쿼리가 Img 파일의 경로를 업데이트하지 않음

2) chkupload.php

입니다

<?php 

session_start(); 
if (!isset($_SESSION["MM_Username"])) 
{ 
    $_SESSION["message"] = "Please Login"; 
} 

?> 
<!--next comes the form, you must set the enctype to "multipart/frm-data" 
and use an input type "file" --> 
<form name="newad" method="post" enctype="multipart/form-data" 
action="chkupload.php"> 
<table> 
    <tr><td><input type="file" name="image"></td></tr> 
    <tr><td><input name="Submit" type="submit" value="Upload image"> 
     </td></tr> 
</table> 
</form> 

insert.php 2 페이지

1.

)가 업로드가 잘 작동한다는 것입니다 & images/folders에 파일을 생성하지만 SQL 테이블에이 파일의 경로를 저장하지 않습니다. 그래서 기본적으로 나는 이것에 도움이 필요하다. 또한 사용자 인증 아래에 있습니다. 그것의 프로필 사진.

<?php require_once('Connections/mb.php'); 

$loginUsername = $_SESSION['MM_Username']; 

//define a maxim size for the uploaded images in Kb 
define ("MAX_SIZE","100"); 

//This function reads the extension of the file. It is used to determine if the 
// file is an image by checking the extension. 
function getExtension($str) { 
     $i = strrpos($str,"."); 
     if (!$i) { return ""; } 
     $l = strlen($str) - $i; 
     $ext = substr($str,$i+1,$l); 
     return $ext; 
} 

//This variable is used as a flag. The value is initialized with 0 (meaning no 
// error found) 
//and it will be changed to 1 if an errro occures. 
//If the error occures the file will not be uploaded. 
$errors=0; 
//checks if the form has been submitted 
if(isset($_POST['Submit'])) 
{ 
    //reads the name of the file the user submitted for uploading 
    $image=$_FILES['image']['name']; 
    //if it is not empty 
    if ($image) 
    { 
    //get the original name of the file from the clients machine 
     $filename = stripslashes($_FILES['image']['name']); 
    //get the extension of the file in a lower case format 
     $extension = getExtension($filename); 
     $extension = strtolower($extension); 
    //if it is not a known extension, we will suppose it is an error and 
     // will not upload the file, 
    //otherwise we will do more tests 
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != 
"png") && ($extension != "gif")) 
     { 
     //print error message 
      echo '<h1>Unknown extension!</h1>'; 
      $errors=1; 
     } 
     else 
     { 
//get the size of the image in bytes 
//$_FILES['image']['tmp_name'] is the temporary filename of the file 
//in which the uploaded file was stored on the server 
$size=filesize($_FILES['image']['tmp_name']); 

//compare the size with the maxim size we defined and print error if bigger 
if ($size > MAX_SIZE*1024) 
{ 
    echo '<h1>You have exceeded the size limit!</h1>'; 
    $errors=1; 
} 

//we will give an unique name, for example the time in unix time format 
$image_name=time().'.'.$extension; 
//the new name will be containing the full path where will be stored (images 
//folder) 
$newname="images/".$image_name; 
//we verify if the image has been uploaded, and print error instead 
$copied = copy($_FILES['image']['tmp_name'], $newname); 
if (!$copied) 
{ 
    echo '<h1>Copy unsuccessfull!</h1>'; 
    $errors=1; 
}}}} 

//If no errors registred, print the success message 
if(isset($_POST['Submit']) && !$errors) 
{ 
    echo "<h1>File Uploaded Successfully! Try again!</h1>"; 
} 



mysql_connect("localhost", "root", "") or die(mysql_error()); 
echo "Connected to MySQL<br />"; 
mysql_select_db("musibridge") or die(mysql_error()); 
echo "Connected to Database"; 
$result = mysql_query("UPDATE artist92 SET path= $newname WHERE email = $loginUsername") 
or die(mysql_error()); 

?> 

오류가 생성 된

공지 사항입니다 : 정의되지 않은 변수 : C에서 _SESSION : 라인 3 파일에 \ XAMPP \ htdocs를 \ MB \ chkupload.php이 성공적으로 업로드! 다시 시도하십시오! MySQL에 연결 데이터베이스에 연결되었습니다. SQL 구문에 오류가 있습니다. 귀하의 MySQL 서버 버전에 해당하는 설명서를 확인하여 올바른 구문을 찾으십시오. 'jpg WHERE email ='at line 1 근처에서 사용하십시오.

문제를 해결하도록 도와주십시오. 테이블 artist92

의 열 경로를 업데이트 그것 업로드하지만이 내 로그인은 세션 변수에 대한 참조 artlog.php

<?php require_once('Connections/mb.php'); ?> 
<?php 
if (!function_exists("GetSQLValueString")) { 
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{ 
    if (PHP_VERSION < 6) { 
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; 
    } 

    $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); 

    switch ($theType) { 
    case "text": 
     $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; 
     break;  
    case "long": 
    case "int": 
     $theValue = ($theValue != "") ? intval($theValue) : "NULL"; 
     break; 
    case "double": 
     $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; 
     break; 
    case "date": 
     $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; 
     break; 
    case "defined": 
     $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; 
     break; 
    } 
    return $theValue; 
} 
} 

$colname_Recordsetartist = "-1"; 
if (isset($_SESSION['MM_Username'])) { 
    $colname_Recordsetartist = $_SESSION['MM_Username']; 
} 
mysql_select_db($database_mb, $mb); 
$query_Recordsetartist = sprintf("SELECT * FROM artist92 WHERE email = %s", GetSQLValueString($colname_Recordsetartist, "text")); 
$Recordsetartist = mysql_query($query_Recordsetartist, $mb) or die(mysql_error()); 
$row_Recordsetartist = mysql_fetch_assoc($Recordsetartist); 
$totalRows_Recordsetartist = mysql_num_rows($Recordsetartist); 
$query_Recordsetartist = "SELECT * FROM artist92"; 
$Recordsetartist = mysql_query($query_Recordsetartist, $mb) or die(mysql_error()); 
$row_Recordsetartist = mysql_fetch_assoc($Recordsetartist); 
$totalRows_Recordsetartist = mysql_num_rows($Recordsetartist); 

$colname_Recordsetartist = "-1"; 
if (isset($_SESSION['MM_email'])) { 
    $colname_Recordsetartist = $_SESSION['MM_email']; 
} 
mysql_select_db($database_mb, $mb); 
$query_Recordsetartist = sprintf("SELECT * FROM artist92 WHERE email = %s", GetSQLValueString($colname_Recordsetartist, "text")); 
$Recordsetartist = mysql_query($query_Recordsetartist, $mb) or die(mysql_error()); 
$row_Recordsetartist = mysql_fetch_assoc($Recordsetartist); 

$colname_Recordsetartist = "-1"; 
if (isset($_SESSION['MM_email'])) { 
    $colname_Recordsetartist = $_SESSION['MM_email']; 
} 
mysql_select_db($database_mb, $mb); 
$query_Recordsetartist = sprintf("SELECT * FROM artist92 WHERE email = %s", GetSQLValueString($colname_Recordsetartist, "text")); 
$Recordsetartist = mysql_query($query_Recordsetartist, $mb) or die(mysql_error()); 
$row_Recordsetartist = mysql_fetch_assoc($Recordsetartist); 
?> 
<?php 
// *** Validate request to login to this site. 
if (!isset($_SESSION)) { 
    session_start(); 
} 

$loginFormAction = $_SERVER['PHP_SELF']; 
if (isset($_GET['accesscheck'])) { 
    $_SESSION['PrevUrl'] = $_GET['accesscheck']; 
} 

if (isset($_POST['email'])) { 
    $loginUsername=$_POST['email']; 
    $password=$_POST['password']; 
    $MM_fldUserAuthorization = ""; 
    $MM_redirectLoginSuccess = "artistprofile.php"; 
    $MM_redirectLoginFailed = "artlog.php"; 
    $MM_redirecttoReferrer = false; 
    mysql_select_db($database_mb, $mb); 

    $LoginRS__query=sprintf("SELECT email, password FROM artist92 WHERE email=%s AND password=%s", 
    GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text")); 

    $LoginRS = mysql_query($LoginRS__query, $mb) or die(mysql_error()); 
    $loginFoundUser = mysql_num_rows($LoginRS); 
    if ($loginFoundUser) { 
    $loginStrGroup = ""; 

    if (PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();} 
    //declare two session variables and assign them 
    $_SESSION['MM_Username'] = $loginUsername; 
    $_SESSION['MM_UserGroup'] = $loginStrGroup;  

    if (isset($_SESSION['PrevUrl']) && false) { 
     $MM_redirectLoginSuccess = $_SESSION['PrevUrl']; 
    } 
    header("Location: " . $MM_redirectLoginSuccess); 
    } 
    else { 
    header("Location: ". $MM_redirectLoginFailed); 
    } 
} 
?> 
+0

세션에 액세스하기 전에'session_start() '를 호출해야 할 수도 있습니다. 그리고 저는 "artist92"가 테이블 이름인지 궁금합니다. – Ohas

+0

예 해당 테이블 이름 – Bhavyanshu

답변

0

첫째, 오메르 이미 말했듯이 그것을 page.Adding된다

$_SESSION 개의 변수를 사용하려면 먼저 session_start()으로 전화해야합니다.

그런 분을 당신의 SQL 쿼리가 실제로 생성하는 것입니다 무슨 생각 :

$newname = "C:\\My Documents\\image.jpg"; 
$loginUsername = "someone"; 
echo "UPDATE artist92 SET path= $newname WHERE email = $loginUsername"; 

출력은 다음과 같습니다

UPDATE artist92 SET path= C:\\My Documents\\image.jpg WHERE email = someone 

어떻게 MySQL은 그 진술을 해석해야합니까? - 그럴 수 없어. 적어도 문자열 주위에 따옴표를 추가해야합니다.

UPDATE artist92 SET path= "C:\\My Documents\\image.jpg" WHERE email = "someone" 

그러나 그것은 여전히 ​​주요 보안 문제입니다. 설명을 보려면 SQL Injection에있는 PHP 기사를 읽어보십시오. 아니, 정말로 - 읽어라!

또한 실제로 파일이 업로드되었는지 확인하지 않습니다. is_uploaded_file()move_uploaded_file() 기능을 확인해야합니다.

+0

도움을 주셔서 감사하지만 여전히 오류가 발생했습니다 알림 : 정의되지 않은 색인 : MM_Username C : \ xampp \ htdocs \ MB \ chkupload.php 5 행 에 있지만 SQL 오류가 없어졌습니다. 나는 또한 내 테이블 artist92을 확인하고 그 경로가 더 이상 SQL 구문에서 오류를 보이지 않는데도 업데이트되지 않았 음을 알게되었습니다. – Bhavyanshu

0

UPDATE 문에서 $ newname 주위에 작은 따옴표가 필요합니다. 그러면 SQL 구문의 오류가 수정됩니다. 또한 "undefined variable : _SESSION"은 session_start()를 호출하여 해결할 수 있습니다.

+0

옙 yup session_start() worked..thanks .. 그리고 thr은 더 이상 구문 오류가 없습니다. .. 나는 이렇게했다 또는 die (mysql_error()); $ 결과 = mysql_query ("업데이트 예술가 92 SET 경로 = '$ 새 이름'어디 이메일 = '$ loginUsername'") ' 하지만 테이블 artist92에서 경로를 업데이트하지 않습니다. 또한 해당 오류를 표시합니다 정의되지 않은 색인 : 5 행의 C : \ xampp \ htdocs \ MB \ chkupload.php에있는 MM_Username MM_username은 세션 변수입니다. – Bhavyanshu

+0

$ _SESSION은 (는) 슈퍼 글로벌이며 세션이 시작되지 않은 경우에도 항상 표시됩니다. 빈 배열 일뿐입니다. –

관련 문제