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

时间:2014-06-05 17:26:27

标签: php mysql sql database mysqli

我是使用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);

2 个答案:

答案 0 :(得分:2)

为什么这条线被注释掉了?您正在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值数组&贯穿始终。执行这两项基本操作至少会在输入数据到达数据库之前对输入数据进行一些基本验证。

答案 1 :(得分:0)

您的查询中的列名称周围有引号。也许你的意思是使用反引号:

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

你也容易受到sql注入攻击。查看mysqli prepared statements