尝试使用php创建表时出错

时间:2014-05-26 13:14:56

标签: php mysql mysqli

我是php的新手,我正在尝试使用mysql创建一个表。当我运行我编写的php代码时,它说:

Warning: mysqli_select_db() expects parameter 1 to be mysqli, string given in /home/engelsmj/public_html/Table/CreateTable.php on line 16
Warning: mysqli_query() expects at least 2 parameters, 1 given in /home/engelsmj/public_html/Table/CreateTable.php on line 23
Notice: Undefined variable: sql in /home/engelsmj/public_html/Table/CreateTable.php on line 25
Warning: mysqli_query(): Empty query in /home/engelsmj/public_html/Table/CreateTable.php on line 25 

创建表时出错:

我相信它正在连接到mysql,但实际创建表时出错了。我已经多次完成了我的代码,但我无法弄清楚它有什么问题以及为什么它不会创建我的表。感谢您对此的任何帮助。

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);

    $con=mysqli_connect("*******","******","*******");
    if (mysqli_connect_errno()) {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    mysqli_select_db("*****", $con);

    mysqli_query("CREATE TABLE Friends(
    idNumber INT NOT NULL AUTO_INCREMENT,  
    Name varchar(30),
    Phone varchar(30), 
    Age int,
    PRIMARY KEY (idNumber))");

    if (mysqli_query($con,$sql)) {
     echo "Friends table created successfully";
    } else {
      echo "Error creating table: " . mysqli_error($con);
    }
    mysqli_close($con);

?>

2 个答案:

答案 0 :(得分:2)

您必须切换这些值:

//Wrong 
mysqli_select_db("*****", $con);

//Right
mysqli_select_db($con, "*****");

至于查询,你必须添加$ sql而不是mysqli_query,因为你稍后会在if语句中这样做:

$sql = "CREATE TABLE Friends(
idNumber INT NOT NULL AUTO_INCREMENT,  
Name varchar(30),
Phone varchar(30), 
Age int,
PRIMARY KEY (idNumber))";

答案 1 :(得分:1)

重新编写代码:

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);

$con=mysqli_connect("*******","******","*******");
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_select_db($con, "*****");

$sql = "CREATE TABLE Friends(
idNumber INT NOT NULL AUTO_INCREMENT,  
Name varchar(30),
Phone varchar(30), 
Age int,
PRIMARY KEY (idNumber))";

if (mysqli_query($con,$sql)) {
 echo "Friends table created successfully";
} else {
  echo "Error creating table: " . mysqli_error($con);
}
mysqli_close($con);
?>