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
Related
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 am trying to get what should otherwise be a simple but of php to insert sample data into a table, but something just isn't having any of it.
Table Definition:
CREATE TABLE IF NOT EXISTS teams (
token varchar(12) COLLATE utf8_unicode_ci NOT NULL,
tname varchar(48) COLLATE utf8_unicode_ci NOT NULL,
captain varchar(64) COLLATE utf8_unicode_ci NOT NULL,
email varchar(64) COLLATE utf8_unicode_ci NOT NULL,
phone varchar(14) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (token),
UNIQUE KEY name (tname),
KEY id (token)
)
ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Code:
$con = mysqli_connect("localhost","username","password","database");
$tname = "Big Bang";
$cname = "Mike";
$cemail = "test#gmail.com";
$cphone = "123-456-7898";
$teamToken = strtoupper(bin2hex(mcrypt_create_iv(6, MCRYPT_DEV_URANDOM)));
$query = "INSERT INTO teams (token, tname, captain, email, phone) VALUES ('" . $teamToken . "', '" . $tname . "', '" . $cname . "', '" . $cemail . "', '" . $cphone . "')";
if (mysqli_query($con, $query))
{
echo "Pass!";
}
else
{
echo $query;
}
mysqli_close($con);
What's odd is the php echos the query, because the mysqli_query result is false, yet the echoed query, when copied and pasted right into phpMyAdmin's terminal, works fine.
I am at my qit's end.
Your Code:
$con = mysqli_connect("localhost","username","password","database");
Edited code:
$con = mysqli_connect("localhost","root","","database");
if(!$con):
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
endif;
Its worked fine on my localhost
Maybe the datatypes of our columns make any problems.
I have once a similar "error" where my token field was to short. phpMyAdmin simply cut the long string to fit (or some thing this) and so it worked inside phpMyAdmin but not with my program.
Please post the CREATE statement of your table.
Try this
mysqli_query($con, $query) or die(mysqli_error($con));
I will suggest go step by step
step 1 : $con = mysqli_connect("localhost","username","password","database");
comment everything other than this statement.
then below write
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
verify your username password and database name (by default:username=="root" password=="" )
step 2 : add the query statements and print it. also check that all values are within their bounds as specified id DB.
step 3 :if $con and $query are valid then you will get your o/p as you req.
If still you have an error please paste your error statement.
using following to connect:
username="root" password=""
Your code works fine in my system.
I used varchar as datatype. Maybe the length of the varchar which you have taken as 12 is less to store the $teamToken variable. Try increasing the size.
Im trying to create tables in mysql dynamically in php
$usernametable="test".$usname;
$create = ("CREATE TABLE $usernametable(
id SMALLINT NOT NULL PRIMARY KEY,
test1 SMALLINT, test2 SMALLINT, test3 SMALLINT )");
$createtable = mysql_query($create, $conn)
or die ('Problem with query' . mysql_error());
It doesnt seem to work and i dont even get an error message. What seems to be the problem?
Try this it is working for me
$con = mysql_connect(<host>,<username>,<password>) or die(mysql_error());
mysql_select_db(<database_name>,$con);
$usernametable="test".$usname;
$create = ("CREATE TABLE $usernametable(
id SMALLINT NOT NULL PRIMARY KEY,
test1 SMALLINT, test2 SMALLINT, test3 SMALLINT )");
$createtable = mysql_query($create, $con)
or die ('Problem with query' . mysql_error());
I've used this script to link to my database account (1&1), using Dreamweaver, which proves to be a successful connection yet cannot seem to create tables for my database when this is linked, was just wondering if anyone has any idea in how to go about the right way with this as I can't seem to get it working.
My database connection which works.
<?php
$hostname="db************";
$database="db********";
$username="db********";
$password="*********";
$link = mysql_connect($hostname, $username, $password);
if (!$link) {
die('Connection failed: ' . mysql_error());
}
else{
echo "Connection to MySQL server " .$hostname . " successful!
" . PHP_EOL;
}
$db_selected = mysql_select_db($database, $link);
if (!$db_selected) {
die ('Can\'t select database: ' . mysql_error());
}
else {
echo 'Database ' . $database . ' successfully selected!';
}
mysql_close($link);
?>
This is the tables script i'm using which doesn't work .
<?php
include_once("php_includes/db_conx.php");
// CREATE TABLE USER
$sql= "CREATE TABLE USER (
id_user_pk INT NOT NULL AUTO_INCREMENT,
nick VARCHAR(40),
email VARCHAR(40),
password VARCHAR(20),
user_reg_date DATE,
PRIMARY KEY (id_user_pk)
) TYPE=INNODB";
mysql_query($sql);
?>
You must use "ENGINE=INNODB" instead of "TYPE=INNODB";
CREATE TABLE `user` (
`id_user_pk` int(11) NOT NULL AUTO_INCREMENT,
`nick` varchar(40) DEFAULT NULL,
`email` varchar(40) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`user_reg_date` date DEFAULT NULL,
PRIMARY KEY (`id_user_pk`)
) ENGINE=INNODB;
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");
?>