这是我的代码。我遇到一个错误,我是PHP的新手。我正在做一个项目,我需要获取输入值并显示在HTML表格中。能否请您推荐一个解决此错误的好方法。
错误:INSERT INTO级别(级别,maxTotal,minTotal,步骤)VALUES(' one',' eight',' two'' 3') 重复输入'一个'关键'等级' 注意:尝试在第7行的H:\ webdev3 \ www \ try2 \ dashBoard.php中获取非对象的属性 0结果
{
public $host;
public $username;
public $password;
public $dab;
public $conn;
public function dbConnect()
{
$this->conn = mysqli_connect($this->host, $this->username, $this->password);
if (!$this->conn) {
die("Connection failed: " . mysqli_connect_error());
} else {
//echo "Connected successfully to server";
}
$db_selected = mysqli_select_db($this->conn, $this->dab);
if (!$db_selected) {
// if the given database doesn't exists
// creates new database with that name
$db_sql = 'CREATE DATABASE userLogin';
// verify the database is created
if (mysqli_query($this->conn, $db_sql)) {
echo "Database userlogin already exists or created successfully\n";
} else {
echo 'Error creating database: ' . mysqli_error() . "\n";
}
}
// creating tables
$table_sql = "CREATE TABLE IF NOT EXISTS users (" . "uid INT PRIMARY KEY AUTO_INCREMENT," . "username VARCHAR(30) UNIQUE," . "password VARCHAR(50)," . "name VARCHAR(100)," . "email VARCHAR(70) UNIQUE); ";
$table_sql = "CREATE TABLE IF NOT EXISTS levels (" . "uid INT PRIMARY KEY AUTO_INCREMENT," . "level VARCHAR(30) UNIQUE," . "maxTotal VARCHAR(50)," . "minTotal VARCHAR(100)," . "steps VARCHAR(70) UNIQUE); ";
$sql = "INSERT INTO levels (level, maxTotal,minTotal,steps) VALUES ('one', 'eight', 'two','three')";
// verify the table is created
if (mysqli_query($this->conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($this->conn);
}
if (mysqli_query($this->conn, $table_sql)) {
// echo "Table: users already exists or created successfully\n";
} else {
echo 'Error creating table: ' . mysqli_error($table_sql) . "\n";
}
}
}
$obj = new dbConfig();
$obj->host = 'localhost';
$obj->username = 'root';
$obj->password = '';
$obj->dab = 'user';
$obj->dbConnect();
答案 0 :(得分:0)
如果您遇到的错误是问题,您可以通过删除&#34; UNIQUE&#34;来解决问题。当您创建表格时,或通过更改&#34; INSERT INTO ...&#34; to&#34; INSERT IGNORE INTO ...&#34;或者不尝试将重复值插入唯一字段。
如果您尝试在用户提交问题时尝试处理此错误,则可以将插入调用嵌套到try / catch语句中,您可以在其中以优雅的方式处理错误。
我不了解您的具体应用或要求,以了解您真正想要的内容。如果你详细说明了预期的结果,我相信我能给你一个更好的答案。
答案 1 :(得分:0)
问题是您有一个唯一的密钥,该表中已经清楚地显示了数据。我注意到你的代码在尝试创建数据之前尝试将数据添加到表中,所以你也应该修复它。并且,由于您覆盖了表创建语句,因此无法创建用户表。
我的建议:重做以上内容,按顺序正确处理数据库或表格不存在或数据不存在的各种情况。在最基本的层面上,您可以无条件地创建CREATE IF NOT EXISTS和INSERT IGNORE。它肯定会简化你的代码。