mysqli, php insert problem
i have an html form that calls a php one. the php inserts data to the sql database. so, this is part of my php code
$name = $_POST['name'];
$query = "INSERT INTO student (complete_name, date_birth, gender, email)
VALUES ( '$name', '$year', '$gender', '$email_1')";
mysqli_query($link,$query) or die(mysql_error());
mysqli_close($link);
and below is my sql code, use to create/use the database
use coursework_test;
drop table if exists Student;
create table Stud开发者_开发百科ent
(
complete_name varchar(50) NOT NULL,
date_birth date,
gender varchar(10) NOT NULL,
email varchar(50) PRIMARY KEY NOT NULL
);
now whenever i run this code, data is inserted ok, but the field "complete_name" remains empty. not null. just empty. any ideas?
In SQL, if you set a column to type varchar and default it to not null, upon insert an empty string ("") will be insert as that data, if no value is given for that column.
That said, I would double check and make sure that $_POST['name']
has the data that you're looking for.
In your HTML code, you properly misnamed the input for name
. So verify the name of that input. Also, some browsers will parse name="name"
as an HTML boolean value, so you might want to find a different name for that field.
That said, you should really think about using prepared statement for your queries. Right now, you are vulnerable to SQL injection attacks with your code. Using prepared statements is simple:
$stmt = mysqli_prepare("INSERT INTO student
(complete_name, date_birth, gender, email)
VALUES (?, ?, ?, ?)", mysqli_stmt_execute($stmt);link);
mysqli_stmt_bind_param($stmt, "s", $name);
mysqli_stmt_bind_param($stmt, "i", $year);
mysqli_stmt_bind_param($stmt, "s", $gender);
mysqli_stmt_bind_param($stmt, "s", $email_1);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
<?php
$host=""; // Host name
$username="users"; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="student"; // Table name
?>
<?php
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$name=$_POST['name'];
$date_birth=$_POST['date_birth'];
$gender=$_POST['gender'];
$email=$_POST['email'];
// Insert data into mysql
$sql="INSERT INTO $tbl_name(name, date_birth, gender, email)VALUES('$name', $year', '$gender', '$email')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='insert.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
// close connection
mysql_close();
?>
精彩评论