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

时间:2015-05-05 14:41:37

标签: php mysql

所以这是我的php文件连接到我的数据库" pizza"

<?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();
}
?>

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

<?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);
?>

有人能看到这里有什么问题吗?

2 个答案:

答案 0 :(得分:0)

替换此行:

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

有了这个:

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

答案 1 :(得分:0)

考虑到您已实例化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