I am trying to pick up a few more marks for my coursework and my teacher said that this will help. When creating a variable or table etc, I want to know how I can code it so that if it already exists it doesn't run the code.
$sql2 = "CREATE TABLE referee(refereeID INT (5) NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(20))";
if (mysqli_query($link, $sql)){
echo "Table created successfully";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
You can try with this query
$sql = "CREATE TABLE IF NOT EXISTS `referee` (
`refereeID` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL default '',
PRIMARY KEY (`refereeID`)
)";
This checks to see if any table like this is in the database.
Hope this helps.
This example sql statement may help you to undersand how to do it
IF NOT EXISTS (SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[YourTable]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[YourTable](
....
....
....
)
END
Related
I want to create tables in mySQL with names that include hyphons, full stops, the % symbol and others. The name will be in a variable called image_name. How do I go about this? Of course I could replace all with underscores, but that is suboptimal. Is the default collation wrong?
My Code:
$image_name = 'abc_def.ghi%';
$sql = "CREATE TABLE $image_name(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
film_name VARCHAR(70) NOT NULL,
...
)";
if(mysqli_query($link, $sql)){
echo "Table of image $image_name created successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
You should surround the table names with backticks - ``
The table name has to surrounded by backticks.
SQL DEMO
CREATE TABLE `abc_def.ghi%` (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
film_name VARCHAR(70) NOT NULL
)
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 5 years ago.
I have a trouble with my mysql. It connects to database but it doesn't make a table. Here is an example of my code:
$db = new mysqli('localhost', 'user.name', 'user.pass', 'db');
if ($db === FALSE) {
echo "ERRROR";
}
$sql = "CREATE TABLE IF NOT EXISTS db (
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) NULL
)";
$db->query($sql);
if (mysqli_query($db, $sql)) {
echo "TABLE CREATED SUCCESSFULLY";
} else {
echo "TABLE CREATED UNSUCCESSFULLY";
}
I appreciate every answer, thank you for help!
MySQL only allows auto-increment columns if they are defined as a key. Given that the column is labelled ID, which means you probably want it as a primary key, try this:
$sql = "CREATE TABLE IF NOT EXISTS db (
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
NAME VARCHAR(20) NULL
)";
Because there is error in MySQL query
CREATE TABLE IF NOT EXISTS db (
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) NULL;
Incorrect table definition; there can be only one auto column and it must be defined as a key
fix :
CREATE TABLE IF NOT EXISTS db (
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) NULL,
key idx_ID(ID)
);
PRIMARY KEY is not compulsory, normal key can work too.
Can you please try this.
$db = new mysqli('localhost', 'user.name', 'user.pass', 'db');
if ($db === FALSE) {
echo "ERRROR";
}
$sql = "CREATE TABLE IF NOT EXISTS db (
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
NAME VARCHAR(20) NULL
)";
$db->query($sql);
if (mysqli_query($db, $sql)) {
echo "TABLE CREATED SUCCESSFULLY";
} else {
echo "TABLE CREATED UNSUCCESSFULLY";
}
i have a table tracker_item that looks like this
tracker_item
id heading trackerid
1 name 1
2 location 1
3 age 1
4 candidate 2
5 area 2
I wish to create different database table according to trackerid using the parameters that are below heading.
E.g acc to the above table tracker_item i want that 2 tables should get created
table1
id name location age
table 2
id candidate area
The code that i tried is
$sql="SELECT * FROM `tracker_item` where trackerid='".$trackerid."' ";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
echo $sql1 = "CREATE TABLE item (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
".
$row['heading']
." VARCHAR(30) NOT NULL,
resume VARCHAR(50)
)";
}
if (mysqli_query($con, $sql1))
{
echo "Table created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
}
output for $sql1 that i got was
CREATE TABLE item (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) NOT NULL, resume VARCHAR(50) )
CREATE TABLE item (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, location VARCHAR(30) NOT NULL, resume VARCHAR(50) )
CREATE TABLE item (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, age VARCHAR(30) NOT NULL, resume VARCHAR(50) )
Instead of multiple tables i would like to get o/p of $sql1 look like the following so that a table can be created in database
CREATE TABLE item ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) NOT NULL, location VARCHAR(30) NOT NULL, age VARCHAR(50) )
Can anyone please tell how it can be done
You just need to modify your while loop and do the CREATE before the loop. You only want the loop to add columns via concatenation:
if(mysqli_num_rows($result)>0)
{
$sql1 = "CREATE TABLE item (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, ";
while($row = mysqli_fetch_assoc($result))
{
$sql1 .= $row['heading']." VARCHAR(30) NOT NULL, ";
}
$sql1 .= "resume VARCHAR(50)) ";
if (mysqli_query($con, $sql1))
{
echo "Table created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
}
Concatenate the entire query in this way and then execute the query.
Output:
CREATE TABLE item (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) NOT NULL, location VARCHAR(30) NOT NULL, age VARCHAR(30) NOT NULL, candidate VARCHAR(30) NOT NULL, area VARCHAR(30) NOT NULL, resume VARCHAR(50))
I hate when people say "I'm not that far along..." or "This site will not be public..." or "It's only for school, so security doesn't matter...". If teachers and professors are not talking about security from day one, they're doing it wrong. Challenge them. They're teaching sloppy and dangerous coding practices which students will have to unlearn later. I also hate it when folks say, "I'll add security later..." or "Security isn't important now..." or "Ignore the security risk...". If you don't have time to do it right the first time, when will you find the time to add it later?
I am working on a project, and I have to use sql. The variable $file_name needs to be the table name, but when i try this:
$sqlTableCreate = "CREATE TABLE ". $file_name . "(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
The table does not create. I checked by using this:
if ($sqlConnection->query($sqlTableCreate) === TRUE) {
echo 'Created Sucessfully';
} else {
echo 'Table does not create.';
}
I get 'Table does not create' when trying to use this. Help would be greatly appreciated. Thanks in advance!
Your filename contains a extension, but I suspect you just want to use the name without the extension as the name of the table. You can use the basename function to remove the extension.
$sqlTableCreate = "CREATE TABLE ". basename($file_name, ".csv") . "(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
If there can be different extensions, and you want to remove them more generally, see
How to remove extension from string (only real extension!)
I don't see any issue with your posted query but couple things may be wrong
Make sure that there is no table exists with that same name. You can use IF NOT EXISTS marker to be sure like
CREATE TABLE IF NOT EXISTS". $file_name . "(
make sure that the variable $file_name is not empty. Else, you are passing a null identifier in CREATE TABLE statement; which will not succeed.
Per your comment: you have $file_name = 'currentScan.csv';
That's the problem here. You are trying to create a table named currentScan.csv which your DB engine thinking that currentscan is the DB name and .csv is the table name which obviously doesn't exits and so the error.
first check your database connection and change your query with given below :
$sqlTableCreate = "CREATE TABLE ". $file_name . " (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
I need to create a large number of tables at once and add data to the first one using PHP and MySQL. My code looks like this:
$sql = "CREATE TABLE table1 (
code VARCHAR(5) PRIMARY KEY,
name VARCHAR(50) NOT NULL
);";
//adding businesses to table
$sql .= "INSERT INTO table1 (code, name)
VALUES ('CODE', 'name');";
//^this basic idea is run a few more times
$sql .= "CREATE TABLE table2 (
code VARCHAR(5) PRIMARY KEY,
name VARCHAR(50) NOT NULL
);";
//^same basic thing run a bunch more times w/ variations to columns
if ($conn->multi_query($sql) === TRUE) {
echo "<p>Tables created.</p>
Continue";
} else {
echo "<p>Error creating tables: " . $conn->error . "</p>";
}
This only creates the first table and adds the data to it, it won't create any other tables and I get no error messages (the success message is shown). I've been googling a solution for an hour and I can't come up with anything. I'm thinking I need a way to hold off creating the next table until the previous one has been created?
I'm very new to MySQL so newbie-friendly would be very much appreciated:)
Try using backticks in your SQL statements, such as:
$sql .= "CREATE TABLE `table2` (
`code` VARCHAR(5) PRIMARY KEY,
`name` VARCHAR(50) NOT NULL
);";
You should also use backticks in your INSERT statement (and your first CREATE query).
If I'm not mistaken, name is reserved word.