我刚开始使用 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);
最佳答案
为什么这行被注释掉了?您在 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
值并在其中滚动。完成这两项基本操作至少可以在输入数据进入数据库之前对其进行一些基本验证。
关于php - 如何使用 MySQLi 向 MySQL 中插入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24066470/