我正在尝试将2个变量插入到我的数据库中。 PHP看起来像这样:
$sql = "INSERT INTO `database`.`table`
(`field1`,
`field2`)
VALUES ('".$field1."','".$field2."') ";
但是,当我尝试运行它时,就像这样:
if (mysqli_query($connection, $sql)) {
echo "New record created successfully";
}
它没有添加到数据库,我收到此错误:
mysqli_query()
期望参数1为mysqli,在第56行的index.php中给出null。
BTW我的连接工作正常,它与此无关,但无论如何它在这里
$connection = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
if(mysqli_connect_errno()) {
exit('Database connection failed: ' . mysqli_connect_error());
}
答案 0 :(得分:2)
要打开数据库连接并查询它,请使用以下代码:
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "INSERT INTO `database`.`table` (`field1`, `field2`) VALUES ('".$field1."', '".$field2."')";
// Perform queries
mysqli_query($con,$sql);
mysqli_close($con);
答案 1 :(得分:0)
我不确定您是否正确设置了连接。 当你得到 - “mysqli_query()期望参数1是mysqli,在第56行的index.php中给出null。”并且此函数的第一个参数必须是连接变量。
请参阅以下
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO `database`.`table` (`field1`, `field2`) VALUES ('".$field1."', '".$field2."')";
// Perform queries
mysqli_query($con,$sql);
mysqli_close($con);
?>
答案 2 :(得分:0)
您创建了一个连接对象,并且正在使用过程样式
使用$connection->query($sql);