无法在PHP中使用pdo插入数据值

时间:2014-09-30 17:51:22

标签: php mysql pdo insert

您好我一直在编写用于将文件上传到服务器的代码 并将值存储在Mysql数据库中 我能够上传文件但面临在MYSQL服务器中插入值的问题

我正在从HTML表单中检索值,并且我已成功获取值并能够从文件中回显 插入代码的表格部分需要帮助

    <?php
require "test.php";
$username=$_POST['username'];
$filename=$_FILES['uploadedfile']['name'];
$language=$_POST['language'];
$comment=$_POST['comment'];

$user_id=$_POST['user_id'];
$filenames=$_FILES['uploadedfile']['name'];

$category=$_POST['category'];
$subcategory=$_POST['subcategory'];
$comment=$_POST['comment'];
$language=$_POST['language'];
$duration=$_POST['duration'];


$domain ='example.com/store/upload/';
$path=$domain.$category.'/'.$filenames;
//$path=$domain.$category.'/'.$filenames;


// Where the file is going to be placed
$target_path = "upload/".$category.'/';

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).
    " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
    echo "filename: " .  basename( $_FILES['uploadedfile']['name']);
    echo "target_path: " .$target_path;
}



echo $filenames."<br />";
echo $domain."<br />";
echo $category."<br />";
echo $path."<br />";
echo $filename."<br />";
echo $language."<br />";
echo $comment."<br />";
echo $subcategory."<br />";
echo $duration."<br />";
echo $user_id."<br />";


// query
try{


$sql="INSERT INTO vup_file(filename,path,category,sub-category,user_id,comment,language,duration)
VALUES (:filename,:path,:category,:subcategory,:user_id,:comment,:language,:duration)";
$query=$conn->prepare($sql);

$query->execute(array(':filename'=>$filename,':path'=>$path,':category'=>$category,':subcategory'=>$subcategory,':user_id'=>$user_id,':comment'=>$comment,':language'=>$language,':duration'=>$duration));
echo 'Inserted';


}catch(PDOException $e)
{
echo 'ERROR OCCURED : '.$e->getMessage();
}


?>    

1 个答案:

答案 0 :(得分:2)

查询中的sub-category列包含连字符。它需要用反引号进行转义。

`sub-category`

在打开连接后立即添加$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);,这会发出错误信号。

SQL正在将其评估为数学问题(减号)。

  • 转换为&#34; sub&#34; minus &#34; category&#34;。

您可以选择使用下划线将列重命名为sub_category,而无需将其转义。


洞察

如果查询/问题中显示的是您的列被称为sub_category而不是sub-category,那么您需要在查询中将其更改为sub_category

  • 或者,如果它被称为subcategory。只有你知道你的专栏叫什么。