I am unable to insert data into MySQL database. I do not know the reason since no error is triggered. I am using XAMPP on windows to run local server. Here is the code. It would be great if someone could help.
I am always getting "Values not inserted" output. I also tried printing the $query when I got exact values I entered through a form in the VALUES ('$email', ...) part of the SQL query.
<?php
$dbconnect = mysqli_connect("localhost","root","","id3626001_login_details");
if (!$dbconnect)
{
die("Connection Failed" .mysqli_connect_error());
}
if (!mysqli_select_db($dbconnect, "id3626001_login_details"))
{
echo "Could not connect to Database";
}
if (isset($_REQUEST['username']) && ($_SERVER["REQUEST_METHOD"] == "POST")){
$username = $_REQUEST['username'];
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];
// Inserting values into the database through a query
$query = "INSERT INTO user_registration (ID, email, username, password) VALUES ('$email', $username', '".md5($password)."')";
if (!mysqli_query($dbconnect, $query))
{
echo "Values not inserted";
}
$result = mysqli_query($dbconnect, $query);
if($result){
echo "Registration Successful";
}
}
?>
there is a problem in your query,
1) your column counts and count of values you are passing are not the same (must be same
2) you forgot to put ' (quote befor $username')
change your query to
// Inserting values into the database through a query
$query = "INSERT INTO user_registration ( email, username, password) VALUES ('$email', '$username', '".md5($password)."')";
When you are testing you should not only print only query, you should also copy that query and run it directly into database through [(localhost/phpmyadmin)> select your databse > SQL ] and see what error are displaying there when firing a query.
UPDATE
for #Akintunde 's suggestion
for security concerns you should not be using these kind of insertion methods which is fully open to SQL injections you must follow some rule to avoid to get your script being target of sql injection
use Prepared Statements instead for database operations
Here in your query you forgot to put upper quote '-> $username',
$query = "INSERT INTO user_registration (email, username, password) VALUES ('$email', '$username', '".md5($password)."')";
Here we are not passing Id as a param so you need to make id auto increment in database for that table.
and why are to passing your query twice into mysqli_query() you can check for once like,
$result = mysqli_query($dbconnect, $query);
if ($result)
{
echo "Registration Successful";
}
else{
echo "Values not inserted";
}
Related
// Do not put any echo code other than the last line.
// didnt include $con in the post.
$userlvlid = $_POST["userlvlid"];
$username = $_POST["username"];
$password = $_POST["password"];
$lname = $_POST["lname"];
$fname = $_POST["fname"];
$mname = $_POST["mname"];
$birthdate = $_POST["birthdate"];
$streename = $_POST["streetname"];
$province = $_POST["province"];
$city = $_POST["city"];
$barangay = $_POST["barangay"];
$organization_name = $_POST["orgname"];
$email_address = $_POST["email_address"];
$license = $_POST["license"];
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
else{
// means connection successful.
echo "sucess";
}
$response = array();
$response["success"] = false;
$sql = "SELECT * FROM users WHERE username = '$username' ";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// means username already exists.
}
else {
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO accounts (`userlvlid`,
`username`,
`password`,
`lname`,
`fname`,
`mname`,
`birthdate`,
`streetname`,
`region`,
`province`,
`city`,
`barangay`,
`orgname`,
`email`,
`license`)
VALUES
('$userlvlid',
'$username',
'$password',
'$lname',
'$fname',
'$mname',
'$birthdate'
'$streetname',
'$region',
'$province',
'$city',
'$barangay',
'$organization_name',
'$email_address',
'$license')";
if (mysqli_query($con, $sql)) {
$response["success"] = true;
}
else {
}
}
}
echo json_encode($response);
?>
Can someone explain why "mysqli_query($con, $sql)" is returning false? I can't find what is wrong in the code. my database contains all of the fields and here maybe a syntax error. The code doesn't give me any errors and it doesn't add the information to the database.
A few things, first this part is not needed:
$sql = "SELECT * FROM users WHERE username = '$username' ";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// means username already exists.
}
Why? Because in between the time that you check for the user's existence and the time that you insert a new record, another client may create a user with the same username. So your second query the insert will fail if it happens (provided of course that you have a unique index on your username as you should).
Secondly, you are not escaping parameters. This leaves you open to SQL injection attacks. And it could also lead to malformed queries that do not get executed correctly - result data is not inserted. Use prepared statements instead.
$sql = mysqli_prepare($con,"INSERT INTO accounts (`userlvlid`,
`username`,
`password`,
`lname`,
`fname`,
`mname`,
`birthdate`,
`streetname`,
`region`,
`province`,
`city`,
`barangay`,
`orgname`,
`email`,
`license`)
VALUES
(?,?,?,?,?,?,?,?,?...)";
Then you need to bind the params
mysqli_bind_params($stmt,('$userlvlid',"ssssssssssssss",
$userlvlid
$username,
$password,
$lname,
$fname,
$mname,
$birthdate,
$streetname,
$region,
$province,
$city,
$barangay,
$organization_name,
$email_address,
$license));
Ugly isn't it? That's why one should use PDO instead of mysqli but using mysqli without prepared statements is just horrible so we have to slog through this.
Now while going through this copy paste, I discovered the real cause of your problem
'$mname',
'$birthdate' /*** no comma here ***/
'$streetname',
Try using echo for the $sql and place the exit after that statement. So that it breaks the query execution after that.
By doing this you can find whether any error is available in the query and you can rectify it.
Note: You first put echo to the Insert Statement and then break the execution by putting the exit; and you copy the statement that is echoed and place it in SQL of the DB and then check whether any error occurs in insertion. If no error occurs remove the echo and delete the exit;
If you have any Table Column mismatch or and Data Discrepancy you can rectify with the help of this echoed query.
Ensure that you provide values that are matching the values that are given into the DB.
**Note: **(E.g) if userlvlid - varchar(11) - You should provide value which is equal to 11 or less than 11 if you enter the value greater than 11 it will not be inserting and the query will fail from there on.
I'm wondering how to insert multiple values into a database.
Below is my idea, however nothing is being added to the database.
I return the variables above (email, serial, title) successfully. And i also connect to the database successfully.
The values just don't add to the database.
I get the values from an iOS device and send _POST them.
$email = $_POST['email'];
$serial = $_POST['serial'];
$title = $_POST['title'];
After i get the values by using the above code. I use echo to ensure they have values.
Now I try to add them to the database:
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = '$email'");
if (mysqli_num_rows($assessorEmail) == 0) {
echo " Its go time add it to the databse.";
//It is unqiue so add it to the database
mysqli_query($connection,"INSERT INTO assessorID (email_address, serial_code, title)
VALUES ('$email','$serial','$title')");
} else {
die(UnregisteredAssessor . ". Already Exists");
}
Any ideas ?
Since you're using mysqli, I'd instead do a prepared statement
if($stmt = mysqli_prepare($connection, "INSERT INTO assessorID (email_adress, serial_code, title) VALUES (?, ?, ?)"))
{
mysqli_stmt_bind_param($stmt, "sss", $email, $serial, $title);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
This is of course using procedural style as you did above. This will ensure it's a safe entry you're making as well.
I have the follow php script for registering a user
<?php
require_once "setting.php";
extract($_REQUEST);
$link = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName);
if (mysqli_connect_errno()){
echo "Connection failed".mysqli_connect_error();
}
$initQuery = "SELECT * FROM users WHERE email = ".$email;
$initResult = mysqli_query($link, $initQuery);
$dbResults = mysqli_fetch_array($initResult, MYSQLI_ASSOC);
if($dbResults == null ){
echo('in the if statement');
$userId = uniqid();
echo($userId);
$query = "INSERT INTO users(email, password, userId) VALUES ($email, $password, $userId )";
echo($query);
$addResult = mysqli_query($link, $query);
echo($addResult);
}
mysqli_free_result($initResult);
mysqli_free_result($addResult);
mysqli_close($link);
?>
The second mysqli_query is not adding a user, I've checked the syntax of the sql statement and it works fine. Does anyone have any ideas?
Also I was thinking about maybe trying to write a mysqli_multi_query to run both queries. I've read that the multi_query will return false if the first query fails, is there anyway to have it execute the second query if the first one fails and not execute the second query if the first one succeeds?
For the love of God, at least put the string values inside quotes if not use prepared statements
"INSERT INTO users(email, password, userId) VALUES ($email, $password, $userId)"
Is invalid. Those string values should be inside quotes
"INSERT INTO users(email, password, userId) VALUES ('$email', '$password', '$userId')"
Please read this before you implement the solution given above:
How can I prevent SQL injection in PHP?
At the very least, please escape the values with mysqli_real_escape_string
Use quotes for your values.
$query = "INSERT INTO users(email, password, userId) VALUES ('$email', '$password', '$userId' )";
$addResult = mysqli_query($link, $query);
If you are facing error than use die function to get the error detail.
$addResult = mysqli_query($link, $query) or die(mysqli_error($link));
It will show you the error also.
Hope this works:
$query = "INSERT INTO users (email, password, userId) VALUES ('$email', '$password', $userId)";
Give a space after table name and all the variables in single quote. :)
UPDATE
Space is not mandatory to give, but would be good for better coding :)
Try to put the values inside quotes.
$query = "INSERT INTO users(email, password, userId) VALUES ('$email', '$password', '$userId' )";
To understand why quotes are mandatory i give an example :).
Mysql supports SELECT from another table for inserted values like in the code below:
INSERT INTO users (email, password, userId)
VALUES
((SELECT email FROM user_info WHERE id = '$userId'),'$password','$userId'))
I am new to using MySQLi. I try to use MySQLi in order to insert data in my database. But does not work. Where may be the error?
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);
Why is line this commented out? You are selecting the database in mysqli_connect("localhost","root","root","kraus") but it makes no sense why that is there:
// mysqli_select_db($con,"kraus");
Should you not have that commented like this?
mysqli_select_db($con,"kraus");
Also there is no space here between registration and the fields in (…) as well as the quotes around your fields:
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
That should be like the following with a space added between the table name & the fields. And since there should just be no quotes around your field names so the final query should be this:
$sql = "INSERT INTO registration (uname, address, password) VALUES ('$firstname', '$lastname', '$age')";
Or perhaps have back ticks like this:
$sql = "INSERT INTO registration (`uname`, `address`, `password`) VALUES ('$firstname', '$lastname', '$age')";
Also, you should really refactor & cleanup your whole codebase like this:
// 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";
Note how I am using mysqli_stmt_bind_param and also setting an array of $_POST values & rolling throughout them. Doing those two basic things at least enforce some basic validation on your input data before it gets to the database.
You have quotes around the column names in your query. Maybe you meant to use backticks instead:
(`uname1`, `address`,...)
You are also vulnerable to sql injection. Look into mysqli prepared statements.
Query is running however not being sent to SQL server.
My Current Register Script.
$link = mysqli_connect("$server", "$user", "$pass", "$webdb");
$username = mysqli_real_escape_string($link, (string) $_POST['username']);
$displayname = mysqli_real_escape_string($link, (string) $_POST['display_name']);
$email = mysqli_real_escape_string($link, (string) $_POST['email']);
$password = sha1((string) $_POST['password']);
$query="INSERT INTO user (`username`, `nicename`, `email`, `password`)
VALUES ('$username', '$displayname', '$email', '$password', '1')";
mysqli_query($link, $query);
mysqli_close($link);
echo $query;
?>
The output I recieve from the Query:
INSERT INTO user (username, nicename, email, password) VALUES ('orion5814', 'Orion5814', 'my#abc.com', '72f2ac484bee398758e769530dd56228d905884d', '1')
I've checked all my link variables and they're all set correctly as far as having the right information in place, so I don't know where else to go from here. Sorry for all the questions; you can view it at doxramos.org if you think it would help at all.
The query is flawed. You name 4 columns (username, nicename, email, password), but you list 5 values ('orion5814','Orion5814','my#abc.com','72f2ac484bee398758e769530dd56228d905884d','1')
If you remove the last value, the query should work.
Also, you could simplify your code by using the object oriented interface to mysqli like this:
$username = $link->real_escape_string($_POST['username']);
and
$link->query($query);
$link->close();
You also don't need to explicitly cast the variables as strings since that is done automatically if needed for your code.
As jordi12100 suggested it is good pratice that you check errors while you connecting to database or executing queries.
You can do it like this:
$link = mysqli_connect("$server", "$user", "$pass", "$webdb") or die( "Error:" . mysqli_connect_error());
mysqli_query($link, $query) or die ("Error:" . mysqli_error($link));
This can give you idea what you did wrong.
Hope this helps.
Probarly an error in your query.
Catch the error with mysqli_error();