Skip to content
Advertisement

PHP, Create a mySQL table with a variable name that includes an underscore

I am trying to create mySQL tables that include php variables for names.

$papername=$_POST['txtpname'];
$papertype=$_POST['txtptype'];

$searchForValue = ',';


if (strpos($papertype, $searchForValue) !== false) {
    
    $str_arr = explode (",", $papertype); 
    
    foreach ($str_arr as $value) {
        
        $value = trim($value);
        
        $value = preg_replace('/s+/', '_', $value);
        
        $value = $papername.'_'.$value;
        
        
        $create=$pdo->prepare("CREATE TABLE ".$value."  (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        product_type VARCHAR(30) NOT NULL, gsm VARCHAR(500) NOT NULL) ;");
        
        $create->execute();
        
    }
    
}

But when I combine two variables with an underscore (line: $value = $papername.’_’.$value;) and give that as the table name, I get an SQL syntax error.

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, product_type VAR...' at line 1 in C:xampphtdocsdesignshopposaddpapertype.php:36 Stack trace: #0 C:xampphtdocsdesignshopposaddpapertype.php(36): PDOStatement->execute() #1 {main} thrown in C:xampphtdocsdesignshopposaddpapertype.php on line 36

However, when I remove line: $value = $papername.’_’.$value;, the query runs fine. Can someone help me with this?

Advertisement

Answer

I think you’re just missing the quotes. It should be escaped using ticks.

$create=$pdo->prepare("CREATE TABLE `".$value."` (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, product_type VARCHAR(30) NOT NULL, gsm VARCHAR(500) NOT NULL) ;");
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement