使用PHP将数据插入MySQL数据库会出错

时间:2016-11-05 08:42:19

标签: php html mysql mysqli

我正在尝试将数据从HTML表单和PHP脚本插入MySQL数据库。

我能够从脚本连接到MySQL服务器,但我无法连接到数据库和表。这样我就无法插入数据。

从PHP脚本触发的错误。错误是“未选择数据库!”。但我已正确宣布这个名字。

我已上传full solution

下面我添加了HTML表单和PHP脚本。

如果可能,请您尝试解决问题。

HTML表单

    <?php

     $dbserver = 'localhost';
     $username = 'root';
     $password = '';

     $dbname = 'car_rental';

     $con = mysqli_connect($dbserver, $username, $password);

     if(!$con)
 {
     echo "Not connected to server !";
     echo 'ERROR : '.mysql_error();

 }else{
     echo "Server connected !";
 }

    if(!mysqli_select_db($con, $dbname));
   {
      echo "Database not selected !";
      echo 'ERROR : '.mysql_error();
  }

   $fname = $_POST["fname"];
   $mname = $_POST["mname"];
   $lname = $_POST["lname"];
   $nicno = $_POST["nicno"];
   $paddress = $_POST["paddress"];
   $email = $_POST["email"];
   $telno = $_POST["telno"];
   $mobileno = $_POST["mobileno"];
   $regdate = $_POST["regdate"];

   $sql = "INSERT INTO new_customers (FirstName, MiddleName, LastName, NICNo, PermanentAddress, EmailAddress, Telephone, Mobile, RegDate) VALUES ('$fname','$mname','$lname','$nicno','$paddress','$email','$telno','$mobileno','$regdate')";

 if (!mysqli_query($con,$sql))
  {
       echo "Data not inserted !";
       echo 'ERROR : '.mysql_error();
  }
  else
  {
     echo "Data inserted !";
  }

   header("refresh:300; url=form.php");

  ?>

InsertData.php

.navbar-brand {
    position: relative;
    background: url(../images/logo.png);
    width: 170px;
    left: 15px;
    background-size: contain;
}

3 个答案:

答案 0 :(得分:1)

尝试

  

QApplication

答案 1 :(得分:0)

试试这个

  

$ pdo = new PDO('mysql:host = localhost; dbname = [databasename]','root','');

答案 2 :(得分:0)

尝试:

<?php

$dbserver = 'localhost';
$username = 'root';
$password = '';
$dbname = 'car_rental';

$con = mysqli_connect($dbserver, $username, $password);

if(!$con) {
    echo "Not connected to server !";
    echo 'ERROR : '.mysqli_error($con);
} else {
    echo "Server connected !";
}

if(!mysqli_select_db($con, $dbname)) {
    echo "Database not selected !";
    echo 'ERROR : '.mysqli_error($con);
}

$fname = $_POST["fname"];
$mname = $_POST["mname"];
$lname = $_POST["lname"];
$nicno = $_POST["nicno"];
$paddress = $_POST["paddress"];
$email = $_POST["email"];
$telno = $_POST["telno"];
$mobileno = $_POST["mobileno"];
$regdate = $_POST["regdate"];

$sql = "INSERT INTO new_customers (FirstName, MiddleName, LastName, NICNo, PermanentAddress, EmailAddress, Telephone, Mobile, RegDate) VALUES ('$fname','$mname','$lname','$nicno','$paddress','$email','$telno','$mobileno','$regdate')";

if (!mysqli_query($con,$sql)) {
    echo "Data not inserted !";
    echo 'ERROR : '.mysqli_error($con);
} else {
    echo "Data inserted !";
}

header("refresh:300; url=form.php");

?>

我还没有测试过它。