gpt4 book ai didi

php - 如何将数据从 PHP 插入到 MariaDB 的列中?

转载 作者:行者123 更新时间:2023-11-29 04:18:28 26 4
gpt4 key购买 nike

我熟悉 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);

最佳答案

您需要使用反引号(不是单引号)将您的表名括起来,因为其中有一个空格。

$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);
}

关于php - 如何将数据从 PHP 插入到 MariaDB 的列中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33266171/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com