我的查询中出现语法错误

时间:2016-06-15 05:48:49

标签: php mysql pdo

这里我有一个文本区域,我将在其中放置一个与此类似的值:

  

Sylhet,Sylhet,Sylhet,Khadim Nagar

     

Sylhet,Sylhet,Sylhet,Mogla Bazar

     

Sylhet,Sylhet,Sylhet,Mullar Gaon

每个逗号分隔字符串包含数据库中四个不同字段的四个值

在我的数据库中有四个字段

bangladesh_info (Division,District,Thana,Union)

我想从我的文本区域捕获值并在各自的字段中添加三行。我编写了以下代码,其中我使用php pdo连接并执行插入命令。我正在

"new records created successfully"

但没有值插入数据库。这里可能出错?我没有收到任何错误!

<?php


if(isset($_POST['text']) && !empty($_POST['text'])){

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myown";
try{
    $conn = new PDO("mysql:host={$servername};dbname={$dbname}", $username, $password);
    $stmt = $conn->prepare("INSERT INTO bangladesh_info (Division,District,Thana,Union)
    VALUES (:division, :district, :thana,:union)");
    $stmt->bindParam(':division', $division);
    $stmt->bindParam(':district', $district);
    $stmt->bindParam(':thana', $thana);
    $stmt->bindParam(':union',$union);
    $myarr=explode("\n",$_POST['text']);
    foreach($myarr as $each){

         list($div,$dis,$tha,$uni)=explode(',',$each);
         echo $uni.'</br>';

         $division=$div;
         $district=$dis;
         $thana=$tha;
         $union=$uni;
         $stmt->execute();

    }
    echo "New records created successfully";

    }
catch(PDOException $e)
    {
    echo "Error: " . $e->getMessage();
    }
}

?>

<html>
<body>
<form action='<?php echo $_SERVER["PHP_SELF"] ; ?>' method='POST' >
     <textarea name='text' id='mytextarea'></textarea>
     <input type='submit' value='submit' >
</form>
<script>

</script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

因为mysql中的Unionreserved keyword,所以它必须是反引号或者将列名更改为其他不在保留关键字列表中的名称

$stmt = $conn->prepare("INSERT INTO bangladesh_info (`Division`,`Distric`,`Thana`,`Union`)
    VALUES (:division, :district, :thana,:union)");