如何使用MySQLi向MySQL插入数据?

问题描述 投票:0回答:2

我是 MySQLi 的新手。我尝试使用 MySQLi 向数据库中插入数据。但不起作用。可能哪里出错了?

echo 'connected';
$con = mysqli_connect("localhost",$username,$password,$database);

// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// mysqli_select_db($con,"kraus");
$firstname = $_POST['uname'];
$lastname =  $_POST['address'];
$age = $_POST['pass'];
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
mysqli_query($con,$sql);
echo "1 record added";


mysqli_close($con);
php mysql sql database mysqli
2个回答
3
投票

为什么这条线被注释掉了?您正在

mysqli_connect("localhost","root","root","kraus")
中选择数据库,但它为什么在那里没有意义:

// mysqli_select_db($con,"kraus");

你不应该这样评论吗?

mysqli_select_db($con,"kraus");

此外,

registration
(…)
中的字段以及字段周围的引号之间没有空格:

$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";

应该如下所示,在表名和字段之间添加一个空格。由于字段名称周围不应该有引号,因此最终查询应该是这样的:

$sql = "INSERT INTO registration (uname, address, password) VALUES ('$firstname', '$lastname', '$age')";

或者也许有这样的回勾:

$sql = "INSERT INTO registration (`uname`, `address`, `password`) VALUES ('$firstname', '$lastname', '$age')";

此外,您应该像这样重构和清理整个代码库:

// Set the connection or die returning an error.
$con = mysqli_connect("localhost","root","root","kraus") or die(mysqli_connect_errno());

echo 'connected';

// Select the database.
// mysqli_select_db($con, "kraus");

$post_array = array('uname','address','pass');
foreach ($post_array as $post_key => $post_value) {
   $$post_key = isset($_POST[$post_value]) && !empty($_POST[$post_value]) ? $_POST[$post_value] : null;
}

// Set the query.
$sql = "INSERT INTO registration (uname, address, password) VALUES (?, ?, ?)";

// Bind the params.
mysqli_stmt_bind_param($sql, 'sss', $uname, $address, $pass);

// Run the query.
$result = mysqli_query($con, $sql) or die(mysqli_connect_errno());

// Free the result set.
mysqli_free_result($result);

// Close the connection.
mysqli_close($con);

echo "1 record added";

注意我如何使用

mysqli_stmt_bind_param
并设置一组
$_POST
值并滚动它们。执行这两项基本操作至少在输入数据到达数据库之前对输入数据强制执行一些基本验证。


0
投票

查询中的列名称有引号。也许您想改用反引号:

(`uname1`, `address`,...)

你也容易受到sql注入的攻击。查看 mysqli 准备好的语句

© www.soinside.com 2019 - 2024. All rights reserved.