尝试使用PHP将数据插入数据库

时间:2022-06-23 14:58:19

So here is my php file that connects to my database "pizza"

所以这是我的PHP文件,连接到我的数据库“披萨”

<?php
//Connect to database
$link = new mysqli('127.0.0.1', 'root', '', 'pizza');
if (!$link) {
    //output this message if connection is unsuccessful
    $output = 'Unable to connect to the database server.';
    exit();
}
?>

Next is my attempt at trying to submit the data

接下来是我尝试提交数据的尝试

<?php
//Include our file that connects us to Pizza database
include("connect.php");

$userAddress = $_POST["address"];
$userPhone   = $_POST["phoneNo"];

//Insert new data into database
$sql = "INSERT INTO orders (address, email, phone) 
         VALUES ('$userAddress',         '$userEmail', '$userPhone')";

if (mysqli_query($sql)) {
    echo "New record created successfully";
} else {
    echo "Error ";
}

mysql_query($sql);
?>

Can anyone see what is wrong here?

有谁能看到这里有什么问题?

2 个解决方案

#1


Replace this line:

替换此行:

if (mysqli_query($sql)) {
   echo "New record created successfully";
}

With this:

if (mysqli_query($link, $sql)) {
   echo "New record created successfully";
 }

#2


Considering you have instantiated a mysqli object, you should use its methods to query your database.

考虑到你已经实例化了一个mysqli对象,你应该使用它的方法来查询你的数据库。

$link = new mysqli('127.0.0.1','root','','pizza');
$query = "INSERT INTO orders (address) VALUES ('$userAddress')";
if ($link->query($query)) {
  //do stuff
}

http://php.net/manual/en/book.mysqli.php

#1


Replace this line:

替换此行:

if (mysqli_query($sql)) {
   echo "New record created successfully";
}

With this:

if (mysqli_query($link, $sql)) {
   echo "New record created successfully";
 }

#2


Considering you have instantiated a mysqli object, you should use its methods to query your database.

考虑到你已经实例化了一个mysqli对象,你应该使用它的方法来查询你的数据库。

$link = new mysqli('127.0.0.1','root','','pizza');
$query = "INSERT INTO orders (address) VALUES ('$userAddress')";
if ($link->query($query)) {
  //do stuff
}

http://php.net/manual/en/book.mysqli.php