Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

php - Insert into a table which has a dash in the name

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:xampphtdocsMar7bamodelsontology_model.php:86 Stack trace: #0 C:xampphtdocsMar7bamodelsontology_model.php(86): PDOStatement->execute(Array) #1 C:xampphtdocsMar7bacontrolersOntology.php(69): Ontology_Model->addRelation('jklljkljk', Array, Array) #2 C:xampphtdocsMar7balibsBookstrap.php(42): Ontology->relationAdd() #3 C:xampphtdocsMar7baindex.php(13): Bootstrap->__construct() #4 {main} thrown in C:xampphtdocsMar7bamodelsontology_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:)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...