本文介绍了如何将数据从PHP插入列到MariaDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉MySql数据库,但是有一个名为MariaDB的新数据库.我尝试从PHP代码中插入数据,但是我不能,所以您可以帮我插入数据吗?我在服务器上的PHP是5.4.32,而我的MySQL版本是10.0.20-MariaDB-cll-live.

I am familiar with MySql databases but there is this new database called MariaDB. I try to insert data there from PHP code and I can't, so can you help me insert the data? My PHP on the server is 5.4.32 and my MySQL version is 10.0.20-MariaDB-cll-live.

这是我用来尝试将数据插入MariaDB的代码.

This is the code that I am using to try to insert data into 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错误.

I used the mysqli code now but it throws me an error 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);

推荐答案

由于表名中有空格,因此需要使用反引号(而不是单引号)引起来. >

You need to use backticks (not single quotes) to surround your table name, since it has a space in it.

$sql = "INSERT INTO `VIP Membership` (Name, Email) VALUES ('$name', '$email')";

更新:您应该真的使用准备好的语句.就目前而言,此代码非常不安全.

UPDATE: You should really be using prepared statements. As it stands, this code is very unsafe.

$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插入列到MariaDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 15:02