sql查询不更新img文件路径

Posted

技术标签:

【中文标题】sql查询不更新img文件路径【英文标题】:Sql Query Not Updating The Path Of Img File 【发布时间】:2012-03-28 08:22:16 【问题描述】:

关于如何通过文件系统上传图像文件并将其路径保存在sql数据库中的教程还没有。 它在一些网站上提到但没有正确解释。 纽约 我正在通过 php 上传图像,我想将上传图像的路径存储在 sql 数据库中。 我有 2 页

1.) 插入.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>

此页面运行良好,但问题出在下一个文件中

2)chkupload.php

问题是上传工作正常,它在 images/ 文件夹中创建文件,但没有将它的路径保存在 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());  

 ?>

产生的错误是

注意:未定义变量:第 3 行 C:\xampp\htdocs\MB\chkupload.php 中的 _SESSION 文件上传成功!再试一次! 连接到 MySQL 连接到数据库您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的“jpg WHERE email =”附近使用正确的语法

请帮我解决这个问题。它上传但不更新表格艺术家92的列路径

这是我的登录页面。添加它仅供您参考会话变量 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 );
  

?>

【问题讨论】:

在尝试访问会话之前,您可能需要致电 session_start()。我只是想知道,“artist92”是表的名称吗? 【参考方案1】:

首先,就像 Omer 已经说过的:

在使用$_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() 函数。

【讨论】:

感谢您的帮助,但我仍然收到错误通知:未定义索引:第 5 行 C:\xampp\htdocs\MB\chkupload.php 中的 MM_Username 但 sql 错误消失了。我还检查了我的表 Artist92,在其中我发现路径没有更新,尽管它不再显示 sql 语法中的任何错误..【参考方案2】:

您需要在 UPDATE 语句中的 $newname 周围加上单引号。这将修复您的 SQL 语法中的错误。 此外,“未定义变量:_SESSION”可以通过调用 session_start() 来解决

【讨论】:

是的 session_start() 工作了..谢谢.. 而且 thr 也不再有语法错误了.. 我这样做了 '$result = mysql_query("UPDATE artist92 SET path= '$newname' WHERE email = '$loginUsername'") 或死(mysql_error()); ' 但它没有更新表 Artist92 中的路径。它还显示错误 Undefined index: MM_Username in C:\xampp\htdocs\MB\chkupload.php on line 5 MM_username is a session variable. $_SESSION 是一个超全局的并且始终存在,即使会话尚未启动。它只是一个空数组。

以上是关于sql查询不更新img文件路径的主要内容,如果未能解决你的问题,请参考以下文章

python 读取文件路径

img src=路径 总是显示不出图片 老是一把XX 新手学网页求解决

Laravel img src 不适用于我的文件路径

img图片显示不出来但是有小标记

SQL查询与修改数据库逻辑文件名,移动数据库存储路径示例

HTML中img标签的src填本地绝对路径无法显示