通过PHP将数据插入MySQL数据库不起作用

时间:2018-09-23 04:17:21

标签: php mysql

很长时间以来,我一直在试图找出如何将数据插入到mySQL数据库中。当我尝试插入数据时,它返回“未选择数据库”。我不太确定代码有什么问题,有人可以检查出来吗?

<?php
$servername = "localhost";
$database= "learnsc2_ts";
$username = "learnsc2_admin";
$password = "Ts@123";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
else {
     echo "Connection successful";
}
$query = "INSERT INTO users(fname, lname) VALUES ('Owen', 
'Feng')";
mysqli_query($conn, $query);
if (mysqli_query($conn, $query)) {
   echo "New record created successfully";
} else {
   echo "Error: " . $query . "<br>" . mysqli_error($conn);?>

3 个答案:

答案 0 :(得分:1)

确保您的数据库名称正确。 我在本地测试了,效果很好。

$servername = "localhost";
$database= "test";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$query = "INSERT INTO users(fname, lname) VALUES ('Owen', 
'Feng')";
$query = mysqli_query($conn, $query);
if ($query) {
   echo "New record created successfully";
} else {
   echo "Error: " . $query . "<br>" . mysqli_error($conn);
}

Here Is the Data

答案 1 :(得分:0)

您忘记添加数据库名称

$conn = new mysqli($servername, $username, $password, $database);

答案 2 :(得分:0)

我知道了。我使用的旧用户名出了点问题。更改为新的用户名和数据库后,解决了!