// 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.
Related
PHP form sending data but SQL shows zeros in all columns.
I checked my code is correct and it prints the result but when I am sending this data to database all the column shows 0 in result. Date of birth is just showing year not complete date.
This is the result of the SQL:
This is my PHP code:
<?php
include('../dbcon.php'); //database included
if (isset($_POST['signup'])) {
$uname = $_POST['uname'];
$email = $_POST['email'];
$fname = $_POST['firstname'];
$lastName = $_POST['lastname'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$password = $_POST['password'];
$qry = "INSERT INTO `registration`(`uname`, `email`, `fname`, `lname`, `dob`, `gender`, `password`) VALUES ('$uname','$email','$fname','$lastName','$dob','$gender','$password')" ; //query taken from the select section of sql form registration.
$run = mysqli_query($dbcon, $qry); //run variable for running the query. $dbcon is database variable
if ($run == true) {
echo "data inserted";
}
else
{
echo "error occurred in registration";
}
}
?>
As others pointed out, you are not escaping your code, so when anyone uses a name or password with a single quote, that person has full control of your database. So don't use PHP-variables in SQL-commands and don't use mysqli. Use PDO and prepared statements. They automatically escape everything and even check for the correct datatype (at least a bit).
TO answer your question, what is the structure of the table (which columns are varchar, int, date,... any unique constrains,...) and can you post one example dataset, which you can't insert with your code?
try
$qry = "INSERT INTO `registration`(`uname`, `email`, `fname`, `lname`, `dob`, `gender`, `password`) VALUES (".$uname.",".$email.",".$fname.",".$lastName.",".$dob.",".$gender.",".$password.")" ;
if no work check before send query
$qry = "INSERT INTO `registration`(`uname`, `email`, `fname`, `lname`, `dob`, `gender`, `password`) VALUES (".$uname.",".$email.",".$fname.",".$lastName.",".$dob.",".$gender.",".$password.")" ;
dd($qry);
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";
}
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 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();