Insert into a table which has a dash in the name

William Kinaan picture William Kinaan · May 15, 2012 · Viewed 7.2k times · Source

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:)

Answer

Shiplu Mokaddim picture Shiplu Mokaddim · May 15, 2012

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