简体   繁体   中英

Can't insert data to MySQL using PHP

I have been trying to get my form data to database through PHP code but it is not working and I have looked at the code a thousandth times for a possible error but couldn't find one as a beginner. The form will actually submit but nothing gets to the database.

Any fast help would be deeply appreciated. Here is the code:

$conn = @mysqli_connect('localhost', 'root', 'aboki'); 
if (mysqli_connect_error()) {
die('Connect Error: ' . mysqli_connect_error());
}

$qry = "INSERT INTO users (email, firstName, surname, userName, password, birthday) values ($email, $firstName, $surname, $userName, $password, $userDOB)";
$result = mysqli_query($conn, $qry); 

try this

$qry = "INSERT INTO users (email, firstName, surname, userName, password, birthday) 
values ('$email', '$firstName', '$surname', '$userName', '$password', '$userDOB')";

Firstly, you are not quoting the values which is why it is not inserting...

This will fix it ( But I strongly recommend you do not use this method!) :

$qry = "INSERT INTO users (email, firstName, surname, userName, password, birthday) values ('$email', '$firstName', '$surname', '$userName', '$password', '$userDOB')";

The Correct Method

You would be better off making the most of the predefined functions that mysqli offers and binding these parameters in a prepared statement like so:

mysqli_prepare($conn,"INSERT INTO users (email, firstName, surname, userName, password, birthday) values (?, ?, ?, ?, ?, ?)");

mysqli_stmt_bind_param($conn, 'TYPES_HERE',$email, $firstName, $surname, $userName, $password, $birthday)

I have solution for data Insert , You can try it out.

$conn= mysqli_connect("localhost", "root", "my_password", "world");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "INSERT INTO users 
(email, firstName, surname, userName, password, birthday) VALUES
($email, $firstName, $surname, $userName, $password, $userDOB)";
 mysqli_query($conn, $query);
 printf ("New Record has id %d.\n", mysqli_insert_id($link));
 mysqli_close($link);

As you having mysqli in Query the syntax quite different,

Feel free to ask further Question.

Thanks

example:

$stmt = mysqli_prepare($conn, "SELECT District FROM City WHERE Name=?")) {
$stmt->bind_param("s", $city);
$stmt->execute();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM