数据不会发布到MySQL数据库

时间:2014-02-15 14:57:58

标签: php mysql sql post

以下是我遇到的错误:

SQL QUERY: INSERT INTO portfolio  (portImg,portTitle,portDesc,portCat,portSkill,portDate) VALUES (IMAGE, TITLE, sadasdasd, CAT, SKILL, 2014-02-15 08:53:10)
Could not enter data: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '
sadasdasd, CAT, SKILL, 2014-02-15 08:53:10)' at line 1

这是我的PHP代码:

<?php

//if form has been submitted process it
if(isset($_POST['submit'])){

    $portImg =$_POST['portImg'];
    $portTitle =$_POST['portTitle'];
    $desc=$_POST['portDesc'];
    $portDesc = trim($desc);
    $portCat=$_POST['portCat'];
    $portSkill=$_POST['portSkill'];
    $portDate=date('Y-m-d H:i:s');

    //very basic validation
    if($portImg ==''){
        $error[] = 'Please enter the title.';
    }
    if($portTitle ==''){
        $error[] = 'Please enter the title.';
    }

    if($portDesc ==''){
        $error[] = 'Please enter the description.';
    }

    if($portCat ==''){
        $error[] = 'Please enter the content.';
    }

    if($portSkill ==''){
        $error[] = 'Please enter the content.';
    }

    if(!isset($error)){

        $query="INSERT INTO portfolio (portImg,portTitle,portDesc,portCat,portSkill,portDate) VALUES ($portImg, $portTitle, $portDesc, $portCat, $portSkill, $portDate)";


        echo "SQL QUERY: ".$query."<br />";


        if (!mysql_query($query))
        {
          die('Could not enter data: ' . mysql_error());
        }
        echo "Entered data successfully\n";
        }

            //redirect to index page
            header('Location: index.php?action=added');
            exit;

        } 

//check for any errors
if(isset($error)){
    foreach($error as $error){
        echo '<p class="error">'.$error.'</p>';
    }
}
?>

这似乎是由Textarea(描述)引起的问题。它似乎是在前后增加空间。有什么想法吗?

4 个答案:

答案 0 :(得分:2)

对于字符串字段,您必须在插入期间用'括起您的值... like:

SQL QUERY: INSERT INTO portfolio (portImg,portTitle,portDesc,portCat,portSkill,portDate)
VALUES ('IMAGE', 'TITLE', 'sadasdasd', 'CAT', 'SKILL', '2014-02-15 08:53:10')

所以你的php应该是

INSERT INTO portfolio (portImg,portTitle,portDesc,portCat,portSkill,portDate)
VALUES ('$portImg', '$portTitle', '$portDesc', '$portCat', '$portSkill', '$portDate')

答案 1 :(得分:0)

你没有消毒你的输入。如果您现在在其中一个字符串中加上双引号(“),则会对您的查询字符串进行转义,并且您会收到无效的查询。

此外,您冒着XSS攻击的风险,因为任何人都可以通过这种方式随意输入查询。

答案 2 :(得分:0)

'sadasdasd'放在单引号中,否则SQL假定它是一个表列

答案 3 :(得分:0)

我猜你已经在你的描述textarea中输入了撇号

尝试使用此

  $portTitle = mysql_real_escape_string($portTitle) ;
  $portDesc = mysql_real_escape_string($portDesc) ;
  ....
  .....//escape other variables also like that.

然后使用它:

 VALUES ('".$portImg."', '".$portTitle."', '".$portDesc."', '".$portCat."', '".$portSkill."', '".$portDate."')