在php中将项插入mysql

时间:2014-05-03 20:15:53

标签: php mysql sql database

尝试在php中将以下内容插入mysql,但不知道为什么它总是返回空查询。 。此外,当我使用phpmyadmin检查表行时,它显示0行。 请帮忙。

// Create a connection to the database via the following variables.
$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);

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


// Insert items into database Inventory
mysqli_query($conn, "INSERT INTO Inventory (ProductName, Quantity, MinStock, MaxStock, Perishable, Supplier,LastInvDate) VALUES ('Peaches', 22, 20, 100, 'TRUE', 'Tree Farms','20140430')");

mysqli_query($conn, "INSERT INTO Inventory (ProductName, Quantity, MinStock, MaxStock, Perishable, Supplier, LastInvDate) VALUES ('Apples', 36, 20, 150, 'TRUE', 'Tree Farms', '20140328')");

mysqli_query ($conn, "INSERT INTO Inventory (ProductName, Quantity, MinStock, MaxStock, Perishable, Supplier, LastInvDate) VALUES ('Paper Towels', 24, 20, 100, 'FALSE', 'Sysco', '20140326')");

mysqli_query ($conn, "INSERT INTO Inventory (ProductName, Quantity, MinStock, MaxStock, Perishable, Supplier, LastInvDate) VALUES ('Snickers', 55, 20, 100, 'FALSE', 'Candy Co', '20140429')");

mysqli_query ($conn, "INSERT INTO Inventory (ProductName, Quantity, MinStock, MaxStock, Perishable, Supplier, LastInvDate) VALUES ('Dish Soap', 17, 20, 100, 'FALSE', 'Clean Co', '20140320')");

mysqli_query ($conn, "INSERT INTO Inventory (ProductName, Quantity, MinStock, MaxStock, Perishable, Supplier, LastInvDate) VALUES ('Coffee', 29, 20, 100, 'FALSE', 'Coffee Co', '20140430')");

mysqli_query ($conn, "INSERT INTO Inventory (ProductName, Quantity, MinStock, MaxStock, Perishable, Supplier, LastInvDate) VALUES ('Newspaper', 21, 20, 100, 'FALSE', 'The Tribune', '20140329')");


//close connection
mysqli_close($conn);

1 个答案:

答案 0 :(得分:0)

如果发生错误,

mysqli_query将返回FALSE,利用它并​​调试问题。此外,只有在连接到数据库时发生错误时才会回显,无论如何都会继续查询数据。

<?php
$con = mysqli_connect($host, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno())
{
    echo "Connect failed: %s\n", mysqli_connect_error();
    exit(); // You don't want to make the query occurr if you actually fail to connect.
}

$query = "INSERT INTO Inventory(ProductName, Quantity, MinStock, MaxStock, Perishable, Supplier, LastInvDate) VALUES (?, ?, ?, ?, ?, ?, ?)"; 
// Using prepared statements is the way to go. HOWEVER I recommend using PDO, there you can use named parameters.
$stmt = $con->prepare($query);
$stmt->bind_param("siiisss", "Peaches", 22, 20, 100, "TRUE", "Tree Farms", "20140430");

$result = $stmt->execute();
if (!$result)
{
    throw new Exception($mysqli->error");
}
else
{
    echo "success.";
}