Insert into a table which has a dash in the name

守給你的承諾、 提交于 2019-11-26 22:04:21

问题


I have a table called concept-relation and I want to insert into it.

for ($i = 0; $i < count($sources); $i++) {
    $sourceID = $this->getConcpeptID($sources[$i]);
    $desID = $this->getConcpeptID($distinations[$i]);
    $query2 = "INSERT INTO concept-relation (relationID, firstConceptID, secondConceptID) VALUES (:rID, :sID, :dID)";
    $sth = $this->db->prepare($query2);
    $sth->execute(array(
        ':rID' => $relationID,
        ':sID' => $sourceID,
        'dID' => $desID
    ));
}

I got this syntax error message

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 '-relation (relationID, firstConceptID, secondConceptID) VALUES (' at line 1' in C:\xampp\htdocs\Mar7ba\models\ontology_model.php:86 Stack trace: #0 C:\xampp\htdocs\Mar7ba\models\ontology_model.php(86): PDOStatement->execute(Array) #1 C:\xampp\htdocs\Mar7ba\controlers\Ontology.php(69): Ontology_Model->addRelation('jklljkljk', Array, Array) #2 C:\xampp\htdocs\Mar7ba\libs\Bookstrap.php(42): Ontology->relationAdd() #3 C:\xampp\htdocs\Mar7ba\index.php(13): Bootstrap->__construct() #4 {main} thrown in C:\xampp\htdocs\Mar7ba\models\ontology_model.php on line 86

I tried to insert directly from MySQL and got error seems the same error

#1064 - 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 '"-".relation (relationID, firstConceptID, secondConceptID) VALU' at line 1

The problem is because the table's name has dash in in, look how MySQL understand the query

INSERT INTO concept - relation(
    relationID,
    firstConceptID,
    secondConceptID
)
VALUES ( 3, 3, 3 )

It understands concept just and make "- relation" alone,

Any help appreciated, but not changing my table's name:)


回答1:


Enclosing identifiers with backtick makes reserved words/characters as valid identifiers in mysql.

So you should use

 `concept-relation`

The backtick (`)is the key at the top-left of this keyboard.




回答2:


$query2 = "INSERT INTO `concept-relation` (relationID, firstConceptID, secondConceptID)
                VALUES (:rID, :sID, :dID)";



回答3:


Try:

"INSERT INTO `concept-relation` (relationID, firstConceptID, secondConceptID) VALUES (:rID, :sID, :dID)";



回答4:


try this

$query2 = "INSERT INTO concept-relation (relationID, firstConceptID, secondConceptID)
                VALUES (:rID, :sID, :dID)";


来源:https://stackoverflow.com/questions/10607041/insert-into-a-table-which-has-a-dash-in-the-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!