I'm trying to use php to add a table to a database I created in MAMP.
I have explored these answers here:
Cannot connect to mysql server with MAMP nor with Community ServerConnect to MySQL in MAMP
I have also tried using this code on a server, this free hosting site called. biz.nf. There I get no connection error, but the table is not created.
Really stumped here, would appreciate any advice, thanks.
<?php
$con = mysql_connect("localhost:3306", "paul", "paul");
mysql_select_db("magusblog", $con);
$table = "ENTRIES";
mysql_query("CREATE TABLE IF NOT EXISTS '$table' ( 'ID' INT NOT NULL AUTO_INCREMENT , PRIMARY KEY ( 'ID' ) )");
mysql_query("ALTER TABLE '$table' ADD 'PHOTO' TEXT NOT NULL");
mysql_query("ALTER TABLE '$table' ADD 'TITLE' TEXT NOT NULL");
mysql_query("ALTER TABLE '$table' ADD 'DATE' TEXT NOT NULL");
mysql_query("ALTER TABLE '$table' ADD 'CONTENT' TEXT NOT NULL");
?>
All of your queries have syntax errors. You do NOT use ' quotes to delimit field names. If you'd bothered actually CHECKING if errors were occuring, you'd have been informed about this:
CREATE TABLE IF NOT EXISTS '$table' ( 'ID' INT NOT NULL AUTO_INCREMENT , PRIMARY KEY ( 'ID' ) )
^-- ^-- ^--^--- ^--^-
remove ALL of the indicated quotes, on ALL of your queries. And then rewrite them as:
$result = mysql_query(...) or die(mysql_error());
Was just a couple of syntax issues... see below.. just tested and successfully created the table. Let me know if any problems.
<?php
$table = "ENTRIES";
mysql_query("CREATE TABLE IF NOT EXISTS " . $table . " (ID INT NOT NULL AUTO_INCREMENT , PRIMARY KEY ( ID ) )");
mysql_query("ALTER TABLE " . $table . " ADD PHOTO TEXT NOT NULL");
mysql_query("ALTER TABLE " . $table . " ADD TITLE TEXT NOT NULL");
mysql_query("ALTER TABLE " . $table . " ADD DATE TEXT NOT NULL");
mysql_query("ALTER TABLE " . $table . " ADD CONTENT TEXT NOT NULL");
?>
Related
I am new to wordpress , I am creating the table but I dont know where is the error occuring , hence table is not creating in database , my table code is below
$table_name = $wpdb->prefix . "myuser";
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
`id` int(11) AUTO_INCREAMENT NOT NULL ,
`name` varchar(50) CHARACTER SET utf8 NOT NULL,
`email` varchar(50) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`id`)
) $charset_collate; ";
and I am inserting data in it but there is no error showing neither the table is creating
$table_name = $wpdb->prefix . "myuser";
$wpdb->insert(
$table_name, //table
array('name' => $name, 'email' => $email), //data
array('%s', '%s') //data format
);
$message.="Users added successfully";
You've only defined the sql query yet, you still need to execute it.
According to this article you can use the following code:
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
Just put it right after the part that starts with $sql =.
Assuming you're writing some kind of plugin, notice you'll also have to add the function as register_activation_hook.
For more information, see Writing a plugin and Creating Tables with Plugins.
I'm writing an simple form in PHP that get input and insert it to database, I had succeeded in creating a database, but not a table. I use Xampp for the database.
Here is my code for creating a table:
mysqli_select_db($DBconnect, $DBname);
$TableName = "Bugtrack";
$SQLstring = "SHOW TABLES LIKE ' " . $TableName . "' ";
if ($stmt = mysqli_prepare($DBconnect, $SQLstring)) {
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if (mysqli_stmt_num_rows($stmt) == 0) {
mysqli_stmt_close($stmt);
$SQLstring = "CREATE TABLE" . $TableName . "(BugID SMALLINT
. NOT NULL AUTO_INCREMENT PRIMARY KEY,
. Game VARCHAR(10), Version VARCHAR(5),
Platform VARCHAR(10), Frequency VARCHAR(5),
proposed_solution TINYTEXT)";
if ($stmt = mysqli_prepare($DBconnect, $SQLstring)) {
$QueryResult = mysqli_stmt_execute($stmt);
if ($QueryResult === FALSE) {
echo "<p>Unable to create the table.</p>"
. "<p>Error code "
. mysqli_errno($DBConnect)
. ": " . mysqli_error($DBConnect)
. "</p>";
}
mysqli_stmt_close($stmt);
}
}
}
Try echoing $SQLstring and run the query in mysql console. It will point you to the exact problem with your query.
Modify this line to $SQLstring = "CREATE TABLE" . $TableName . "(BugID SMALLINT to $SQLstring = "CREATE TABLE " . $TableName . " (BugID SMALLINT
Instead of checking $SQLstring = "SHOW TABLES LIKE ' " . $TableName . "' "; you can check it like $SQLstring = "CREATE TABLE " . $TableName . " if not exists (BugID SMALLINT
If you are using XAMPP, go to localhost/phpmyadmin using your webbrowser.
Select your database, then select sql.
To create your table.
CREATE TABLE Bugtrack (
BugID INT(8) NOT NULL AUTO_INCREMENT PRIMARY KEY,
Game VARCHAR(10), Version VARCHAR(5),
Platform VARCHAR(10),
Frequency VARCHAR(5),
proposed_solution TINYTEXT
)
If you really want to do it with php. I would use PDO.
$username = 'me';
$password = 'my_super_secret_password';
$dsn = 'mysql:host=localhost;dbname=my_database';
$conn = new PDO($dsn, $username, $password);
$sql = 'CREATE TABLE Bugtrack (
BugID INT(8) NOT NULL AUTO_INCREMENT PRIMARY KEY,
Game VARCHAR(10), Version VARCHAR(5),
Platform VARCHAR(10),
Frequency VARCHAR(5),
proposed_solution TINYTEXT
)';
$conn->execute($sql);
OR
Go to localhost/phpmyadmin, click on you database on the left hand side. You will see an option to create a table. I also would make sure that you have permission for the database that you created. To do that, while you are in phpmyadmin, click your database, select the privileges tab that is almost at the top of the page. From there just follow the prompts.
I'm trying to create a table if it does not already exist in my database. For this I'm running this test which is working as intended:
$conn = mysql_connect("localhost", "twa222", "twa222bg");
mysql_select_db("airline222", $conn) or die ("Database not found " . mysql_error() );
$val = mysql_query("SELECT 1 from '$FLIGHTID'");
However my problem comes when I try to create the table itself, which is giving me the following error:
Problem with query: 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 ''passenger' SMALLINT NOT NULL, 'booking' CHAR(6), 'seat' VARCHAR(3))' at line 2
This is the code that is attempting to generate the table
if(!$val)
{
$sql = "CREATE TABLE ".$FLIGHTID." (
passenger SMALLINT NOT NULL PRIMARY KEY,
booking CHAR(6), seat VARCHAR(3) )";
$rs = mysql_query($sql) or die ("Problem with query" . mysql_error());
}
mysql_close($conn);
I originally thought it was the ".$FLIGHTID." that was causing the problem but when I changed that to simply be ABC I still got the same error.
Can anyone see where I am going wrong?
EDIT:
My SQL output when using ABC is:
CREATE TABLE ABC ( passenger SMALLINT NOT NULL PRIMARY KEY, booking CHAR(6), seat VARCHAR(3) )
Without using ABC it is:
CREATE TABLE ( passenger SMALLINT NOT NULL PRIMARY KEY, booking CHAR(6), seat VARCHAR(3) )
You use single quotes arround column names what is not allowed. Single qoutes indicates that the value inside is a litaral:
Change:
$val = mysql_query("SELECT 1 from '$FLIGHTID'");
to:
$val = mysql_query("SELECT 1 from $FLIGHTID");
Use mysqli_*or PDOinstead of deprecated mysql_* API.
I'm doing a bit of MySQL using commands through PHP only (without using the phpMyAdmin interface to create the tables) and I'm having a bit of a problem creating Primary and Foreign keys. This is my current code.
<?php
$conectar = mysql_connect("localhost", "root", "") or die (mysql_error());
//mysql_query("CREATE DATABASE DataBaseTeste") or die(mysql_error());
mysql_select_db("DataBaseTeste") or die(mysql_error());
mysql_query("CREATE TABLE Pergunta("
. "id_Pergunta INT AUTO_INCREMENT,"
. "Descricao TEXT,"
. "Nivel VARCHAR,"
. "PRIMARY KEY(id_Pergunta),"
. "FOREIGN KEY(id_Assunto) REFERENCES Assunto(id_Assunto))")Or die(mysql_error());
mysql_query("CREATE TABLE Aluno("
. "id_Aluno INT NOT NULL,"
. "AlunoNome CHAR,"
. "Grupo CHAR,"
. "PRIMARY KEY(id_Aluno))")Or die(mysql_error());
mysql_query("CREATE TABLE Assunto("
. "id_Assunto INT,"
. "Descricao VARCHAR,"
. "PRIMARY KEY(id_Assunto))")Or die(mysql_error());
mysql_close();
?>
I also tried using this (without the FOREIGN KEY, by just inserting the other table's id):
$conectar = mysql_connect("localhost", "root", "") or die (mysql_error());
//mysql_query("CREATE DATABASE DataBaseTeste") or die(mysql_error());
mysql_select_db("DataBaseTeste") or die(mysql_error());
mysql_query("CREATE TABLE Pergunta("
. "id_Pergunta INT AUTO_INCREMENT,"
. "Descricao TEXT,"
. "Nivel VARCHAR,"
. "PRIMARY KEY(id_Pergunta),"
. "id_Assunto INT)")Or die(mysql_error());
The error message I get is this:
"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 'PRIMARY KEY(id_Pergunta)..."
It's probably something pretty stupid but I can't figure it out.
First, try to use lowercase names, I just did it for PKs
Then to use foreign keys you must add the column name do that table which will hold the FK
Also then, you need to use INNODB, can't remember if MyIsam allows you FK, but I recommend it, note that INNODB will create an index for them too.
CREATE TABLE assunto(
id_assunto INT,
descricao VARCHAR(254),
PRIMARY KEY(id_assunto)
)ENGINE=INNODB;
CREATE TABLE aluno(
id_aluno INT NOT NULL,
alunoNome CHAR(254),
grupo CHAR,
PRIMARY KEY(id_aluno)
)ENGINE=INNODB;
CREATE TABLE pergunta(
id_pergunta INT AUTO_INCREMENT,
id_assunto int,
descricao TEXT,
nivel VARCHAR(254),
PRIMARY KEY(id_pergunta),
FOREIGN KEY(id_assunto) REFERENCES assunto(id_assunto)
)ENGINE=INNODB;
Let me add you a PHP version, note the execution order.
<?php
$conectar = mysql_connect("localhost", "root", "") or die (mysql_error());
//mysql_query("CREATE DATABASE DataBaseTeste") or die(mysql_error());
mysql_select_db("DataBaseTeste") or die(mysql_error());
mysql_query("CREATE TABLE aluno("
. "id_aluno INT NOT NULL,"
. "alunoNome CHAR,"
. "grupo CHAR,"
. "PRIMARY KEY(id_aluno))")Or die(mysql_error());
mysql_query("CREATE TABLE assunto("
. "id_assunto INT,"
. "descricao VARCHAR,"
. "PRIMARY KEY(id_assunto))")Or die(mysql_error());
mysql_query("CREATE TABLE Pergunta("
. "id_pergunta INT AUTO_INCREMENT,"
. "id_assunto INT AUTO_INCREMENT,"
. "descricao TEXT,"
. "Nivel VARCHAR,"
. "PRIMARY KEY(id_pergunta),"
. "FOREIGN KEY(id_assunto) REFERENCES assunto(id_assunto))")Or die(mysql_error());
mysql_close();
This is a working sqlfiddle Mysql 5.1, I use 5.5.32 but show as 5.1 will work too.
http://sqlfiddle.com/#!8/f88b5/3
I have an Auto increment ID column in my table and it does work fine when I insert the records using PHP. I have to delete the records from this table every hour using the DELETE statement. I changed the PHP.ini file and restarted the machine. For some reason Auto increment ID started from '1' again. There were no records in the table when I restarted the machine. I am using PHP 5.3.8 and MySQL 5.5.21 running under IIS. Please let me know if there are any suggestions. Here is my table schema.
CREATE TABLE `test_table` (
`test_id` int(11) NOT NULL AUTO_INCREMENT,
`test_date` datetime DEFAULT NULL,
`test_location` varchar(2000) NOT NULL,
`test_summary` varchar(4000) NOT NULL,
`create_dtm` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`test_id`)
) ENGINE=InnoDB
Here is my insert query
$Sql = "INSERT INTO test_table(test_date, test_location, test_summary) VALUES ('" .sDate. "', '" .$location. "', '" .$summary. "')";
$Result = mysql_query($Sql) or die(mysql_error());
$new_id = MySql_Insert_Id();
Here is DELETE.
$Sql1 = "DELETE FROM test_table";
$Result1 = mysql_query($Sql1) or die(mysql_error());
Using a DELETE with no where clause is the same as TRUNCATING a table, hence they both reset the Next AutoIndex value for the table. (Which is what people would normally want / expect)
Could use something like the following to get around this in your case maybe:
mysql_query(
sprintf(
"ALTER TABLE tbl_name AUTO_INCREMENT = %d",
mysql_insert_id() + 1
) );
(If the DELETE clears the insert value then you will just need to cache it before your DELETE / TRUNCATE)