所以我有这个脚本只是为了在我的数据库中创建一个表。我已经从我现在正在使用的旧脚本中复制了它。怎么这个不工作?任何人?
我得到的错误是"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 "'= varchar (20) NOT NULL, column_two = int NOT NULL auto_increment, column_thre' at line 2"
<?php
include("server_connect.php");
mysql_select_db("assignment5");
$create = "CREATE TABLE tbltable (
column_one = varchar (20) NOT NULL,
column_two = int NOT NULL auto_increment,
column_three = int NOT NULL,
column_four = varchar (15) NOT NULL,
column_five = year,
PRIMARY KEY = (column_one)
)";
$results = mysql_query($create) or die (mysql_error());
echo "The tables have been created";
?>
答案 0 :(得分:8)
删除已建议的所有=
:
$create = "CREATE TABLE tbltable (
column_one varchar (20) NOT NULL,
column_two int NOT NULL auto_increment PRIMARY KEY,
column_three int NOT NULL,
column_four varchar (15) NOT NULL,
column_five year
)";
每个表都应有一个主键,您必须将AUTO_INCREMENT
列指定为PRIMARY KEY
。在这种情况下,AUTO_INCREMENT
列为column_two
,我将其设置为PRIMARY KEY
。
答案 1 :(得分:2)
MySQLi程序
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to create table
$sql = "CREATE TABLE MyGuests (
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 (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
<强>(PDO)强>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
// use exec() because no results are returned
$conn->exec($sql);
echo "Table MyGuests created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
答案 2 :(得分:0)
解决方案是将所有权限分配给BD用户,如下所示:
GRANT ALL PRIVILEGES ON *. * TO 'user_name' @ 'localhost';