在查询中使用PHP变量时MySQL错误1064

时间:2015-08-20 09:08:34

标签: php mysql

session_start()

我收到错误1064?我已经阅读了类似问题的答案,但我的代码不起作用。我的表架构是:

<?php
    session_start();
    $con = mysqli_connect("localhost","root","12369","medical");
    $data1 = $_SESSION["symp1"];
    $data2 = $_SESSION["symp2"];
    $data3 = $_SESSION["symp3"];
    $data4 = $_SESSION["symp4"];
    $finalData = implode(' ', array($data1, $data2, $data3, $data4));
    $userinput = $_REQUEST["answer"];
    $dname=$_SESSION["dname"];
    $dname = str_replace(' ', '_', $dname);
    echo $dname."  <br>";
    $sql = " UPDATE diseases SET UserInput = $finalData WHERE Name =   $dname ";
    if($userinput=='yes'){  
        if(mysqli_query($con,$sql)){
            echo "Values inserted";
            $_SESSION["info"] = "yes";
            header('Location: http://localhost/medical/last.php');
    }else{
            echo mysqli_errno($con);
            $_SESSION["info"] = "no";
            //header('Location: http://localhost/medical/last.php');
    }
   }
?>

我的代码有什么问题?感谢

3 个答案:

答案 0 :(得分:3)

变化:

$sql = " UPDATE diseases SET UserInput = $finalData WHERE Name =   $dname ";

为:

$sql = "UPDATE `diseases` SET `UserInput` = '$finalData' WHERE `Name` = '$dname'";

在包含字符串的变量周围添加单引号。 在列和表周围添加反引号以防止mysql保留字错误

使用mysqli_prepare执行以下操作会更好:

$stmt = mysqli_prepare($con, "UPDATE `diseases` SET `UserInput` = ? WHERE `Name` = ?");
mysqli_stmt_bind_param($stmt, "ss", $finalData, $dname);
mysqli_stmt_execute($stmt);

答案 1 :(得分:1)

正如错误消息所述,您的SQL语法中有错误:

  

MySQL错误1064:您的SQL语法错误

用单引号包围你的数据,你很高兴。此外,$loginUrl = $fb->getLoginUrl( 'https://example.com/fb-callback.php', array('scope' => '') ); reserved keyword in MySQL。但是,您仍然可以在查询中使用它,但是您应该考虑使用反引号转义表名:

Name

答案 2 :(得分:0)

在数据周围添加单个qoutes:

 $sql = " UPDATE diseases SET UserInput = '$finalData' WHERE Name =   '$dname' ";

或更好地使用准备好的陈述