I have an html form in which a person fills an input field. The input field will then be sent to the PHP form handler. The form handler will then process it and the variable input in the html form will then become the name of an SQL table. Everything is okay except that part of making the variable the name of SQL table.
Look at my code:
<?php error_reporting(E_ALL); ini_set('display_errors', 1);?>
<?php $title =$_POST['myfile']?>
<?php $info =$_POST['info']?>
<?php $tags =$_POST['tags']?>
<?php $category =$_POST['category']?>
<?php $allowcomments =$_POST['allowcomments']?>
<?php $flagging =$_POST['flagging']?>
<?php $visibility =$_POST['visibility']?>
<?php $date =$_POST['date']?>
<?php $name =$_POST['name']?>
<?php $size =$_POST['size']?>
<?php $type =$_POST['type']?>
<?php $path =$_POST['path']?>
<?php $sub =$_POST['sub']?>
<?php $cap =$_POST['cap']?>
<?php
$servername='localhost';
$username='root';
$password='you aint gonna know my password!!';
$dbname = "galaxall";
$conn = new mysqli($servername, $username, $password, $dbname);
#mysql_select_db('galaxall');
?>
<?php $title =$_POST['myfile']?><br>
<?php echo $title?><br>
<?php echo $info?><br>
<?php echo $tags?><br>
<?php echo $category?><br>
<?php echo $allowcomments?><br>
<?php echo $visibility?><br>
<?php echo $flagging?><br>
<?php echo $cap ?>
<?php echo $date ?>
<?php echo $name ?>
<?php echo $size ?>
<?php echo $type ?>
<?php echo $sub ?>
<?php echo $cap ?>
<?php $file=$_POST['myfile']?>
<?php
$sql="INSERT INTO `galaxall_uploads` (`ID`, `Title`, `Producer`, `Description`, `Tags`, `Type`, `Category`, `Allow comments`, `Flag offensive comments`, `Date`, `Visibility`,`Size`,`Path`,`Subtitles_source`,`Captions_source`) VALUES (NULL, '$title', '', '$info', '$tags', '$type', '$category', '$allowcomments', '$flagging', '$date', '$visibility','$size','$path','$cap','$sub')";
$sql2="CREATE TABLE $title `Comments` ( `ID` BIGINT(255) NOT NULL AUTO_INCREMENT , `Commenter` VARCHAR(255) NOT NULL , `Comment` TEXT NOT NULL , `Date/time` DATETIME NOT NULL , `Likes` BIGINT(255) NOT NULL , `Dislikes` BIGINT(255) NOT NULL , `Replies number` BIGINT(255) NOT NULL , PRIMARY KEY (`ID`)) ENGINE = InnoDB;";
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
<?php
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn->query($sql2) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
?>
<html>
The file has been uploaded
</html>
The var $title has been declared and I an even echo it.But when i try to make it the name of the table(sql2),I get the error
2018-07-20 New record created successfullyError: CREATE TABLE title `Commentsss` ( `ID` BIGINT(255) NOT NULL AUTO_INCREMENT , `Commenter` VARCHAR(255) NOT NULL , `Comment` TEXT NOT NULL , `Date/time` DATETIME NOT NULL , `Likes` BIGINT(255) NOT NULL , `Dislikes` BIGINT(255) NOT NULL , `Replies number` BIGINT(255) NOT NULL , PRIMARY KEY (`ID`)) ENGINE = InnoDB;
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 '`Commentsss` ( `ID` BIGINT(255) NOT NULL AUTO_INCREMENT , `Commenter` VARCHAR(25' at line 1 The file has been uploaded
So how do I make a PHP variable the name of a table?
i don't want to get in your database design but the error you are facing is about string concatenation and an issue on having a space in the table name:
$sql2="CREATE TABLE `$title_Comments` ( `ID` BIGINT(255) NOT NULL AUTO_INCREMENT , `Commenter` VARCHAR(255) NOT NULL , `Comment` TEXT NOT NULL , `Date/time` DATETIME NOT NULL , `Likes` BIGINT(255) NOT NULL , `Dislikes` BIGINT(255) NOT NULL , `Replies number` BIGINT(255) NOT NULL , PRIMARY KEY (`ID`)) ENGINE = InnoDB;";
this will fix the error you mention in your question
EDIT: looking at the comments I can suggest you to have a single table for comments where you store the comment, the id of the user that does the comment and the id of the video they are commenting on. As I said, no need for a custom table each time
Related
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 3 years ago.
there is some problem with my code. Everytime I try to insert something into the database, I get the syntax error.
Here is my database structure:
CREATE TABLE `notes` (
`id` int(12) NOT NULL,
`type` varchar(15) NOT NULL,
`title` varchar(43) NOT NULL,
`text` varchar(43) NOT NULL,
`group` varchar(32) NOT NULL,
`uid` int(64) NOT NULL,
`creator` int(64) NOT NULL,
`insert_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `notes`
ADD PRIMARY KEY (`id`);
ALTER TABLE `notes`
MODIFY `id` int(12) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=79;
And thats my code
<?php
session_start();
require '../config.php';
$notetype = $_POST['type'];
$notetitle = $_POST['title'];
$notetext = $_POST['text'];
$notegroup = $_POST['group'];
$noteuid = $_POST['uid'];
$notecreator = $_POST['creator'];
$notetbname = $note['tbname'];
$conn = new mysqli($databaseconfig['ip'], $databaseconfig['user'], $databaseconfig['pass'], $databaseconfig['dbname']);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO $notetbname (type, title, text, group, uid, creator)
VALUES ('$notetype', '$notetitle', '$notetext', '$notegroup', $noteuid, $notecreator);";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
This is what I get as error message:
Error: INSERT INTO notes (type, title, text, group, uid, creator) VALUES ('player', 'Hello there', 'Good morning everybody', 'Cop', 3325, 103);
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 'group, uid, creator) VALUES ('player', 'Hello there', 'Good morning everybody'' at line 1
This is because group is a mysql's reserved word.
change the fieldname or try this (notice the backtick " ` " before and after the word group:
$sql = "INSERT INTO $notetbname (type, title, text, `group`, uid, creator)
VALUES ('$notetype', '$notetitle', '$notetext', '$notegroup', $noteuid, $notecreator);";
Here you can find a list of all reserved word (mysql 5.5)
https://dev.mysql.com/doc/refman/5.5/en/keywords.html#keywords-5-5-detailed-G
Hey I am trying to make a guestobook with two tables. First table is for: the users (User_ID[primary key], Name, Mail, Password) and the second table is for the comments: (Comment_ID [foreign key], Message, Date).
Now I am trying to reference from User_ID to Comment_ID. But I am getting the Error: No Database selected.
$db = "dbname";
$tblGuestbookUsr = "tblGuestbookUsr";
$tblGuestobookComment = "tblGuestobookComment";
// parent tbl
$sql = "CREATE TABLE IF NOT EXISTS `$db`.`$tblGuestbookUsr`
( `Usr_ID` INT NOT NULL AUTO_INCREMENT ,
`Name` VARCHAR(150) NOT NULL ,
`Mail` TEXT NOT NULL ,
`Password` VARCHAR(20) NOT NULL ,
PRIMARY KEY (`Usr_ID`)) ENGINE = InnoDB;";
if (mysqli_query($conn, $sql)) {
echo "Succes <br />";
} else {
echo "Error: " . mysqli_error($conn). "<br />";
}
// child tbl
$sql = "CREATE TABLE IF NOT EXISTS `$db`.`$tblGuestobookComment` (
`Comment_ID` INT NOT NULL ,
`Nachricht` LONGTEXT NOT NULL ,
`Datum` DATE NOT NULL ,
FOREIGN KEY (Comment_ID) REFERENCES $tblGuestbookUsr(Usr_ID) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB;";
if (mysqli_query($conn, $sql)) {
echo "Succes <br />";
} else {
echo "Error: " . mysqli_error($conn). "<br />";
}
I am trying to execute the following query
DROP TABLE IF EXISTS `developer_messenger`;
CREATE TABLE `developer_messenger` (
`id` int(10) NOT NULL,
`title` varchar(45) NOT NULL,
`username` varchar(45) NOT NULL,
`message` varchar(45) NOT NULL,
`type` varchar(45) NOT NULL,
`date_time` varchar(45) NOT NULL,
`status` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
But this simple query is showing me Error in PHP
Could not get data: 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 'CREATE TABLE developer_messenger ( id int(10)
NOT NULL, title varchar(' at line 1
I am a newbie, Sorry if its silly,
Help Appreciated!
In Response to your second question about magic_quotes:
if (!get_magic_quotes_gpc()) { //checks php ini if magic_quotes is not on
$title = addslashes($_POST['title']);
}
else
{
$title = stripslashes($_POST['title']);
}
addslashes(); http://php.net/manual/en/function.addslashes.php
stripslashes(); http://php.net/manual/en/function.stripslashes.php
not sure if this helps but it might that way you dont have to change php.ini
just the $data that is to be entered into sql
Your query is correct, Try exciting DROP and CREATE one by one.
This code may help you.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE `developer_messenger` (
`id` int(10) NOT NULL,
`title` varchar(45) NOT NULL,
`username` varchar(45) NOT NULL,
`message` varchar(45) NOT NULL,
`type` varchar(45) NOT NULL,
`date_time` varchar(45) NOT NULL,
`status` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
I am trying to create a "setup script" for my website. I would like to create the database, adding tables and some content at the same time. So far this is how I did it, but it seems kind off messy using multiple queries:
<?php
$servername = "localhost";
$username = "root";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE MYDB";
if ($conn->query($sql) === TRUE) {
echo "1. Database created successfully <br/>";
$conn->select_db("MYDB");
$sql_members = "CREATE TABLE MEMBERS (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(40) NOT NULL,
DISCOUNT VARCHAR(5),
PASSW CHAR(128),
ROLE VARCHAR(9)
)";
if ($conn->query($sql_members) === TRUE) {
echo "2. Table MEMBERS created successfully <br/>";
} else {
echo "Error creating table: " . $conn->error;
}
$sql_content = "CREATE TABLE CONTENT (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TITLE VARCHAR(30) NOT NULL,
TEXT VARCHAR(30) NOT NULL
)";
if ($conn->query($sql_content) === TRUE) {
echo "3. Table CONTENT created successfully <br/>";
} else {
echo "Error creating table: " . $conn->error;
}
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
Is there a better way?
Thanks!
== UPDATE ==
I have tried to export the database and use the resulted .sql file as my setup query, but something is wrong, I get:
Error creating tables: 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 'INSERT INTO CONTACTS (ID, NAME, PHONE,
EMAIL, ADDRESS, CITY, `COUN' at line 12
CREATE TABLE IF NOT EXISTS `CONTACTS` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(25) COLLATE utf8_romanian_ci NOT NULL,
`PHONE` varchar(16) COLLATE utf8_romanian_ci NOT NULL,
`EMAIL` varchar(35) COLLATE utf8_romanian_ci NOT NULL,
`ADDRESS` text COLLATE utf8_romanian_ci NOT NULL,
`CITY` varchar(16) COLLATE utf8_romanian_ci NOT NULL,
`COUNTRY` varchar(16) COLLATE utf8_romanian_ci NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_romanian_ci AUTO_INCREMENT=2 ;
INSERT INTO `CONTACTS` (`ID`, `NAME`, `PHONE`, `EMAIL`, `ADDRESS`, `CITY`, `COUNTRY`) VALUES
(1, 'Peter Brown', '0742062307', 'office#shop.com', 'Avenue 13.', 'Santaclaus', 'Austria');
== SOLUTUION ==
I needed "multi_query()" for executing my multiple queries.
You can try this too :p
$errors = [];
$table1 = "CREATE TABLE MEMBERS (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(40) NOT NULL,
DISCOUNT VARCHAR(5),
PASSW CHAR(128),
ROLE VARCHAR(9)
)";
$table2 = "CREATE TABLE CONTENT (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TITLE VARCHAR(30) NOT NULL,
TEXT VARCHAR(30) NOT NULL
)";
$tables = [$table1, $table2];
foreach($tables as $k => $sql){
$query = #$conn->query($sql);
if(!$query)
$errors[] = "Table $k : Creation failed ($conn->error)";
else
$errors[] = "Table $k : Creation done";
}
foreach($errors as $msg) {
echo "$msg <br>";
}
You could export the whole database including all tables using the command line or using PhPMyAdmin. Then query the content of the file in php to create the database.
you can create a file and put all your sql queries in it..
CREATE TABLE MEMBERS (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(40) NOT NULL,
DISCOUNT VARCHAR(5),
PASSW CHAR(128),
ROLE VARCHAR(9)
);
CREATE TABLE CONTENT (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TITLE VARCHAR(30) NOT NULL,
TEXT VARCHAR(30) NOT NULL
);
then in your php code:
$query = file_get_contents ('queries.sql');
if ($conn->query($query) === TRUE) {
echo "all tables created successfully <br/>";
} else {
echo "Error creating tables: " . $conn->error;
}
This is what I have so far.... I do not understand why it is not working? Any ideas? This is just a simple script to connect to a database, create a table and insert some data. I also want to retrieve the data but I think I may be jumping a little a head.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
if (mysql_query("CREATE_DATABASE nogjhghkgst98", $link))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
if ($link="CREATE TABLE contactsZ8 (id int(6) NOT NULL auto_increment,first varchar(15) NOT NULL,last varchar(15) NOT NULL,phone varchar(20) NOT NULL,mobile varchar(20) NOT NULL,fax varchar(20) NOT NULL,email varchar(30) NOT NULL,web varchar(30) NOT NULL,PRIMARY KEY (id),UNIQUE id (id),KEY id_2 (id))") {
echo "ineserted";
}
else
{
echo "not inserted" . mysql_error();
}
$link = "INSERT INTO contactsZ VALUES ('','John','Smith','01234 567890','00112 334455','01234 567891','johnsmith#gowansnet.com','http://www.gowansnet.com')";
$link="SELECT * FROM contactsZ";
$link=mysql_query($link);
mysql_close($link);
?>
There is definitely something wrong:
if ($link="CREATE TABLE contactsZ8 (id int(6) NOT NULL auto_increment,first varchar(15) NOT NULL,last varchar(15) NOT NULL,phone varchar(20) NOT NULL,mobile varchar(20) NOT NULL,fax varchar(20) NOT NULL,email varchar(30) NOT NULL,web varchar(30) NOT NULL,PRIMARY KEY (id),UNIQUE id (id),KEY id_2 (id))") {
an assignment in an if
query not executed (that is not so bad: once the table is created, executing again the query when reloading the page will fail)
assigning to $link ! this is confusing (but should not generate any error)...
Then :
$link = "INSERT INTO contactsZ VALUES ('','John','Smith','01234 567890','00112 334455','01234 567891','johnsmith#gowansnet.com','http://www.gowansnet.com')";
The query is not executed.
Edit: the INSERT is done in contactsZ, whereas the CREATE TABLE creates contactsZ8.
Edit2: And finally:
mysql_close($link);
After re-assigning 3 times $link, $link is not the (optional, by the way) link identifier any more...