I\'m pretty new to php.. and this is probably a stupid mistake... but I have no idea what is going on. I\'m trying to create a table in my database using php. I want to name
// Create MySql table with variable
$tableName = "tb-"."$userEmail";
$tName="Beta";
$createTable = "CREATE TABLE ".$tName." ( UserName varchar(30), UserPassword varchar(30) )" ;
This above syntax works. Apply this example to your code. Please review some error in your concatenation
Add this after your SQL querys - (It really helps and speeds up error correcting time)
or die("A MySQL error has occurred.<br />Error: (" . mysql_errno() . ") " . mysql_error());
echos this in your instance:
A MySQL error has occurred.
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 '' . ' ID
INT NOT NULL AUTO_INCREMENT PRIMARY KEY, ' . ' please
VARCH' at line 1
This then indicates to me that the error regards " & '.
After changing the code to contain single quotes and executing it, there is now no echo.
<?php
$tableusername = "philip";
$create = "CREATE TABLE `".$tableusername."` ("
. " `ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, "
. " `please` VARCHAR(50) NOT NULL, "
. " `make` VARCHAR(50) NOT NULL, "
. " `this` VARCHAR(50) NOT NULL, "
. " `work` VARCHAR(50) NOT NULL"
. " )"
. " ENGINE = myisam;";
mysql_query($create)or die("A MySQL error has occurred.<br />Error: (" . mysql_errno() . ") " . mysql_error());
?>
Note: Please refer to the MySQLi extension when using SQL embedded in PHP. mysql_* is in a deprecation process.
Hope this helps.
you have invalid concatenation of string, use double quotes
instead of single quotes
.
$create = "CREATE TABLE `".$tableusername."` ("
. " `ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, "
. " `please` VARCHAR(50) NOT NULL, "
. " `make` VARCHAR(50) NOT NULL, "
. " `this` VARCHAR(50) NOT NULL, "
. " `work` VARCHAR(50) NOT NULL' "
. " )"
. " ENGINE = myisam;";
Use a heredoc:
$create = <<<SQL
CREATE TABLE `$tableusername` (
`ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`please` VARCHAR(50) NOT NULL,
`make` VARCHAR(50) NOT NULL,
`this` VARCHAR(50) NOT NULL,
`work` VARCHAR(50) NOT NULL
)
ENGINE = myisam;
SQL;
Notably, you can use string interpolation in a heredoc, but you should really tend toward parametrized queries.