3

I'm trying to dynamically create tables in MySQL, using CodeIgniter PHP framework:

if($colname != ''){
            $str = "CREATE TABLE IF NOT EXISTS $colname (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), site_id INT NOT NULL, name BLOB NOT NULL)ENGINE=INNOBD;";
            $query = $this->db->query($str);

When I execute that from the MySQL command prompt, it created the table perfectly. However, if it's done through CodeIgniter, I'm getting the following error:

<body>
    <div id="container">
        <h1>A Database Error Occurred</h1>
        <p>Error Number: 1064</p><p>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 ''tc 11' (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), site_id INT NOT NULL, ' at line 1</p><p>CREATE TABLE IF NOT EXISTS 'tc 11' (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), site_id INT NOT NULL, name BLOB NOT NULL)ENGINE=INNOBD;</p>

What's going on here? Thanks

cybertextron
  • 10,547
  • 28
  • 104
  • 208

4 Answers4

2

You are using quotes ' and not backticks `` ` to surround your table name. MySQL uses backticks to escape names.

You should change the value of $colname from

'tc 11'

To this:

`tc 11`

You can do that with:

$colname = str_replace("'", "`", $colname);

Other resources that confirm this:

(Sorry about the code blocks; SO has an issue with backticks inside inline code)

Community
  • 1
  • 1
Bailey Parker
  • 15,599
  • 5
  • 53
  • 91
0

that is because you are passing an incorrect value in $colname

First i assume $colname is supposed to be $tablename, because this is a query to create a table.

and it seems like there is a space in your table name, please show what value you have in your $colname variable.

there should be no space, TC_11

Ibu
  • 42,752
  • 13
  • 76
  • 103
0

try:

"CREATE TABLE IF NOT EXISTS `".str_replace(' ','',$colname)."` (id...
mgraph
  • 15,238
  • 4
  • 41
  • 75
0

There is an error in your sql query. The following code should do the job and also make it safer.

if(!empty($colname))
{
    $sql = "CREATE TABLE IF NOT EXISTS ? (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), site_id INT NOT NULL, name BLOB NOT NULL)ENGINE=INNOBD;";
    $query = $this->db->query($sql,array($colname));
}
Kush
  • 1,512
  • 2
  • 17
  • 32