我有这个连接到我的数据库的脚本,并且有一个用于创建数据库的catch case(如果不存在),目前sql connect中的错误似乎没有触发try catch
$host = "localhost";
$username = "root";
$password = "";
$database = "webscrp";
try {
$con = mysqli_connect(
$host,
$username,
$password,
$database
);
}
catch (Exception $e) {
$conE = mysqli_connect(
$host,
$username,
$password
);
$q1 = "CREATE DATABASE webscrp";
$q2 = "CREATE TABLE product
(
ProductID int NOT NULL AUTO_INCREMENT,
ProductName varchar(500),
ProductDescription varchar(2000),
ProductPhotoLink varchar(200) NULL,
ProductPrice decimal(10,2),
ProductCategory varchar(300),
ProductStock int(100),
ProductDatePosted timestamp DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (ProductID)
)";
mysqli_query($conE, $q1);
mysqli_query($conE, $q2);
$con = mysqli_connect(
$host,
$username,
$password,
$database
);
}
我在我的数据库中尝试了SQL并且执行正常。
答案 0 :(得分:1)
当您无法连接到数据库时,它会生成警告而不是异常。所以执行不会去catch语句,因为这里没有异常。你应该这样做:
<?php
$con = mysqli_connect(
$host,
$username,
$password,
$database
);
if(!$con) {
$con = mysqli_connect(
$host,
$username,
$password
);
$q1 = "CREATE DATABASE $database";
mysqli_query($conE, $q1);
$con = mysqli_connect(
$host,
$username,
$password,
$database
);
}
$q2 = "CREATE TABLE product
(
ProductID int NOT NULL AUTO_INCREMENT,
ProductName varchar(500),
ProductDescription varchar(2000),
ProductPhotoLink varchar(200) NULL,
ProductPrice decimal(10,2),
ProductCategory varchar(300),
ProductStock int(100),
ProductDatePosted timestamp DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (ProductID)
)";
mysqli_query($con, $q2);
?>