用户创建的数据库或表

时间:2013-05-29 03:37:02

标签: php database mysqli

我需要创建一个数据库,用户输入名字和姓氏,然后将其记录到可以按字母顺序排序的表格中。

我认为这是PHP表格的主要内容:

    <?php
$con=mysqli_connect("mysql6.000webhost.com","owen","*********","student");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

// Create table
$sql = "CREATE TABLE Persons (PID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(PID), FirstName CHAR(15), LastName CHAR(15))";

// Execute query
if (mysqli_query($con,$sql))
  {
  echo "Table persons created successfully";
  }
else
  {
  echo "Error creating table: " . mysqli_error($con);
  }
?>

接下来,我有实际的html代码,用户提交了他或她的名字:

<!DOCTYPE HTML>

<html>
    <head>
        <link rel="shortcut icon" href="http://2.bp.blogspot.com/-W6qoXhCjKSs/Tpul-XAR3-I/AAAAAAAACeU/Oe1ZEzpnUCg/s1600/sbstweb.gif">
        <link rel="stylesheet" type="text/css" href="../style.css">
        <title>Almost Done!</title>
    </head>

    <body>
        <img class= "logo" src= "http://2.bp.blogspot.com/-W6qoXhCjKSs/Tpul-XAR3-I/AAAAAAAACeU/Oe1ZEzpnUCg/s1600/sbstweb.gif">
        <h1>Enter your name below to complete the quiz</h1>  
        <form action="insert.php" method="post">
            <p><input autofocus name="firstname" placeholder="First Name" type="text"></p>
            <p><input autofocus name="lastname" placeholder="Last Name" type="text"></p>
            <input type="submit">
        </form>
    </body>
</html>

最后,我认为PHP代码会将新条目插入数据库:

<?php
$con=mysqli_connect("mysql6.000webhost.com","a3159217_owen","*********","a3159217_student");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="INSERT INTO Persons (FirstName, LastName)
VALUES
('$_POST[firstname]','$_POST[lastname]')";

if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
echo "1 record added";

mysqli_close($con);
?>

我的第一个问题是如何让PHP代码实现和工作。当我在网页上点击提交时,它会将我引导到我创建的insert.php代码。如何让它提交到数据库,以及如何创建数据库。

其次,要实际显示表,我是否必须创建另一个呈现PHP表的html页面?这是如何工作的?

1 个答案:

答案 0 :(得分:0)

我不确定这会有所帮助。 但是对于MYSQL,为了连接数据库,代码如下。

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);

for mysqli,

$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";

您可以参考http://php.net/manual/en/function.mysql-connect.phphttp://php.net/manual/en/mysqli.quickstart.connections.php