So I am having trouble inserting data into my database. The current error I have is a "No database selected" error but I can't see where the issue is. My code is:
<?php
$con=mysqli_connect("localhost","root","","db_test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$firstname=$_POST['firstnameReg'];
$surname=$_POST['surnameReg'];
$mypassword=$_POST['passwordReg'];
$email=$_POST['emailReg'];
$result= mysql_query("INSERT INTO tbl_customers (firstname, lastname, email, password) VALUES ('$firstname', '$surname', '$email', '$mypassword'");
echo "$firstname", "$surname", "$mypassword", "$email";
if($result)
{
echo "Success!";
}
else
{
die(mysql_error());
}
mysqli_close($con);
?>
Can you see any errors? I know it's not protected against SQL injection, it's just a test project. Thank you.
Instead of mysql_query
which is from the wrong library, you should use mysqli_query
$result= mysql_query("INSERT INTO tbl_customers (firstname, lastname, email, password) VALUES ('$firstname', '$surname', '$email', '$mypassword'");
So in your case, you're also missing the closing parenthesis from the VALUES
:
$result = mysqli_query($con, "INSERT INTO tbl_customers (firstname, lastname, email, password) VALUES ('$firstname', '$surname', '$email', '$mypassword')");
Taking the opportunity you should also implement prepared statement to avoid SQL injection:
$sql = "INSERT INTO tbl_customers (firstname, lastname, email, password) VALUES (?, ?, ?, ?)";
if (!$insert = $con->prepare($sql))
die('Query failed: (' . $con->errno . ') ' . $con->error);
if (!$insert->bind_param('ssss', $firstname, $surname, $email, $mypassword))
die('Binding parameters failed: (' . $insert->errno . ') ' . $insert->error);
if (!$insert->execute())
die('Execute failed: (' . $insert->errno . ') ' . $insert->error);
else
echo "Success!";
mysqli_close($con);
You're using both mysqli
and mysql
in your code. You can and should only be using mysqli
.
Go to php.net and find each mysql_
syntax you want to use in mysqli_
.
Every warning you see, that the mysql_
syntax is deprecated, shows the function that is going to be used instead.
For instance: mysqli_connect()
replaces both mysql_connect();
and mysql_select_db();
(asks for server and database in one function).
Don't worry about editing, almost all the important functions are (almost) the same so you don't have to edit that much.