我得到“没有数据库选择”错误甚至被选中

时间:2017-04-04 18:01:04

标签: php mysql crud

我是MySql和PHP的新手,我试图制作一个CRUD,但每当我尝试将数据插入到名为“studenti”的表中时,我得到的错误是我没有选择数据库但是我选择了一个带有mysqli_select_db的数据库($ con, “d_base”);

有人请帮助我因为我不明白为什么它不起作用'

这是代码;

$id = $_POST['ID'];
$nota = $_POST['Nota'];
$emri = $_POST['Emri'];
$mbiemri = $_POST['Mbiemri'];



$servername = "localhost";
$dbname = "d_base";

// 1.Create connection
$con = mysqli_connect("localhost","d_base");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  if (!mysqli_query($con,"INSERT INTO studenti (id, nota, emri, mbiemri) VALUES ('$id', '$nota','$emri','$mbiemri')"))
  {
  echo("Error description: " . mysqli_error($con));
  }

// Perform queries 
mysqli_select_db($con, "d_base");
mysqli_query($con,"INSERT INTO studenti (id, nota, emri, mbiemri) VALUES ('$id', '$nota','$emri','$mbiemri')");
mysqli_close($con);

1 个答案:

答案 0 :(得分:0)

在此之前,如果您是初学者,请直接PDO或使用mysqli准备好的陈述更安全。

以下是您的php和html表单必须如何显示和工作的示例。

首先,您必须检查是否按下了提交按钮,如果其按下的读取值形成$_POST个变量。

第二件事你必须使用函数mysqli_real_escape_string()将注释转义到你的mysql。

之后尝试插入查询并检查错误,如果没有错误查询将成功插入。

PHP代码

<?php

// set error report ; 1 = on | 0 = off
error_reporting(1);

$db_host = "localhost"; // host
$db_user = "root";      // database username
$db_pass = "";          // database password
$db_name = "d_base";    // database name

// 1.Create connection
$con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);

// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// if form is submited
if (isset($_POST['submit']))
{
    // escape post variables
    $id = mysqli_real_escape_string($con, $_POST['ID']);
    $nota = mysqli_real_escape_string($con, $_POST['Nota']);
    $emri = mysqli_real_escape_string($con, $_POST['Emri']);
    $mbiemri = mysqli_real_escape_string($con, $_POST['Mbiemri']);

    // make query
    $query = mysqli_query($con, "INSERT INTO studenti (id, nota, emri, mbiemri VALUES ('$id', '$nota', '$emri', '$mbiemri')")

    // check for query
    if (!$query)
    {
        echo "Error description: " . mysqli_error($con);
    }
    else
    {
        echo "Query inserted.";
    }

    // close connenction
    mysqli_close($con);
}


?>

<form action="" method="post">
   <input type="text" name="ID" placeholder="Id"><br />
   <input type="text" name="Nota" placeholder="Nota"><br />
   <input type="text" name="Emri" placeholder="Emri"><br />
   <input type="text" name="Mbiemri" placeholder="Mbiemri"><br />
   <input type="submit" name="submit" value="Submit form">
</form>