我熟悉MySql数据库,但有一个名为MariaDB的新数据库。我尝试从PHP代码插入数据而我不能,所以你可以帮我插入数据吗?我在服务器上的PHP是5.4.32,我的MySQL版本是10.0.20-MariaDB-cll-live。
这是我用来尝试将数据插入MariaDB的代码。
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server
$db = mysql_select_db("database", $connection); // Selecting Database from Server
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$name = $_POST['name'];
$email = $_POST['email'];
if($name !=''||$email !=''){
//Insert Query of SQL
$query = mysql_query("insert into VIP Membership(Name, Email) values ('$name', '$email')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection); // Closing Connection with Server
编辑:我现在使用了mysqli代码,但它却给我一个错误500。
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "db_table";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$name = $_POST['name'];
$email = $_POST['email'];
if($name !=''||$email !=''){
$sql = "INSERT INTO 'VIP Membership' (Name, Email)
VALUES ('$name', '$email')";
if(mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn);
答案 0 :(得分:5)
你需要使用反引号(不是单引号)来包围你的表名,因为它有一个空格。
$sql = "INSERT INTO `VIP Membership` (Name, Email) VALUES ('$name', '$email')";
更新:你应该真正使用预备语句。就目前而言,这段代码非常不安全。
$sql = mysqli_prepare($conn, "INSERT INTO `VIP Membership` (Name, Email) VALUES (?, ?)");
if($sql !== FALSE){
mysqli_stmt_bind_param($sql, "ss", $name, $email);
if(mysqli_stmt_execute($sql)){
echo "New record created successfully";
} else {
echo mysqli_stmt_error($sql);
}
} else{
echo mysqli_error($conn);
}
答案 1 :(得分:1)
MariaDB是MySQL的向后兼容,二进制替代品。这意味着MariaDB版本将与MySQL完全一样。您不必做任何特定的事情来使您的MySQL代码在MariaDB上运行。但是在我的代码中,我会使用mysqli
函数(或PDO)而不是旧的已弃用的mysql
函数。
由于您可能会遇到一些不兼容问题,因此您可以查看此官方文档,了解两者之间的差异。 MariaDB vs MySQL
答案 2 :(得分:-1)
检查方括号{在此处插入代码}如果未正确安排,则会导致错误