I'm having trouble with the following code:
$sql= "INSERT INTO Users(Username, Password, Lastname, Email) VALUES
('$hash', '$lastname', '$email', '$email')";
mysqli_query($MyConnection, $sql);
if(!mysqli_query($MyConnection, $sql)) {
echo 'We are sorry, there are some problems with saving your data. Please try again within a few minutes.';
}
else {
echo 'We have succesfully saved your data. An activation e-mail will now be send to the e-mail address that you
have provided us.';
}
I get no direct errors as due to mistyping or misusing a function. I do get however the message of the if-statement in a failure, the "We are sorry(..)" text.
There must be a problem with the execution of the mysqli_query($MyConnection, $sql) function. But I don't see where it is.
P.S. I can't post images, because my reputation is below 10. (Which is quite weird to limit it to that point)
As some of you have provided most / all of the code:
<?php
// Opens the connection of the MySQL Database
$MyConnection = mysqli_connect('fdb6.biz.nf', '1446018_amp', '-')
or die("Could not connect to the database, please try again");
mysqli_select_db($MyConnection,'Users');
mysqli_connect_errno();
// Website Url:
$website = 'http://www.askmephilosophy.co.nf/';
// Information provided by the user
$username = $_POST['username'];
$password = $_POST['password']; // Will get encrypted.
$lastname = $_POST['lastname'];
$email = $_POST['email'];
// A higher "cost" is more secure but consumes more processing power
$cost = 5;
// Create a random salt
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
// Prefix information about the hash so PHP knows how to verify it later.
// "$2a$" Means we're using the Blowfish algorithm. The following two digits are the cost parameter.
$salt = sprintf("$2a$%02d$", $cost) . $salt;
// Hash the password with the salt
$hash = crypt($password, $salt);
$sql= "INSERT INTO Users(Username, Password, Lastname, Email) VALUES
('$hash', '$lastname', '$email', '$email')";
mysqli_query($MyConnection, $sql);
var_dump(mysqli_error($MyConnection));
if(mysqli_query($MyConnection, $sql)) {
echo 'We have succesfully saved your data. An activation e-mail will now be send to the e-mail address that you
have provided us.';
}
else {
echo 'We are sorry, there are some problems with saving your data. Please try again within a few minutes.';
mysqli_error($MyConnection);
}
mysqli_close($MyConnection);
?>
$sql= "INSERT INTO Users(Username, Password, Lastname, Email) VALUES
('$hash', '$lastname', '$email')";
This is your first issue; your table has four columns, and you're passing it three. This query is guaranteed to fail.
mysqli_query($MyConnection, $sql);
if(!mysqli_query($MyConnection, $sql)) {
You're calling the query function twice. You can do this with a single call:
if(!mysqli_query($MyConnection, $sql)) {
// add some error handling code here
// store the return value of mysqli_error() somewhere
echo 'We are sorry, there ar....';
Since you're using mysqli_, you should also be using prepared statements; I hope at least you're sanitising the database inputs before you try to add them to the database.
Why do you only have 3 values, it doesn't match the number of items you are trying to Insert (4) ...
$sql= "INSERT INTO Users(Username, Password, Lastname, Email) VALUES
('$username', '$hash', '$lastname', '$email')";
EDIT:
I would probably write it like this
$sql= "INSERT INTO Users(Username, Password, Lastname, Email) VALUES
({$username}, {$hash}, {$lastname}, {$email})";
EDIT:
Your password cannot be '-'
I would update your connection info like so:
$db = new mysqli('fdb6.biz.nf', 'user', 'pass', 'Users');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
EDIT AGAIN:
$myConnection = new mysqli('fdb6.biz.nf', 'user', 'pass', '1446018_amp');
$myConnection->mysqli_select_db($MyConnection,'Users');
try adding, I think you forgot this. Values always have to equal to columns
$sql= "INSERT INTO Users(Username, Password, Lastname, Email) VALUES
('$username', '$hash', '$lastname', '$email')";
First of all you are inserting twice that records, as there are two instances of mysqli_query($MyConnection, $sql);. You can just remove the first.
The problem here is that you are inserting 3 values in 4 fields.
Anyway you can get the specific error with
mysqli_error($MyConnection);
Add it at the end your echo forever or var_dump(mysqli_error($MyConnection)); in a new line.
Related
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 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.
When my form is submitted (via Ajax), I'm getting the following error message:
[17-Oct-2012 11:46:29] PHP Warning: mysqli_query() [<a href='function.mysqli-query'>function.mysqli-query</a>]: Empty query in /home1/xenongro/public_html/testing/enrolment/thanks.php on line 32
I have a suspicion that it's something to do with the if/else statements, but not sure what the actual problem is.
Can anyone help?
<?php
$firstname = htmlspecialchars(trim($_POST['fname']));
$lastname = htmlspecialchars(trim($_POST['lname']));
$worktel = htmlspecialchars(trim($_POST['worktel']));
$dbc = mysqli_connect('localhost', 'xxxxx', '<xxxx>', 'xxxx')
or die ('Could not connect to MySQL server.');
if ($level != "IOSH Managing Safely"){
if ($funding == "Self Funding"){
$query = "INSERT INTO enrolments (fname, lname, worktel)" .
"VALUES ('$firstname', '$lastname', '$worktel')";
}
else if ($funding == "Employer Funding"){
$query = "INSERT INTO enrolments (fname, lname, worktel)" .
"VALUES ('$firstname', '$lastname', '$worktel')";
}
}
else if ($level == "IOSH Managing Safely"){
if ($funding == "Self Funding"){
$query = "INSERT INTO enrolments (fname, lname, worktel)" .
"VALUES ('$firstname', '$lastname', '$worktel')";
}
else if ($funding == "Employer Funding"){
$query = "INSERT INTO enrolments (fname, lname, worktel)" .
"VALUES ('$firstname', '$lastname', '$worktel')";
}
}
$result = mysqli_query($dbc, $query)
or die ('error querying database');
mysqli_close($dbc);
?>
try
var_dump($query);
var_dump($funding);
just before
$result = mysqli_query($dbc, $query);
it'll give you more information
I suspect that $funding might have slight variation to your constant strings
might be typo / extra space / cap case
There are two situation where no query is being set:
the level does not match the string, or the funding does not match the string.
It might be a problem with the spaces.
Worse, you don't use mysql_real_escape_string and unless magic_quotes_gpc is on, this allows an attacker to inject his SQL.
$funding doesn't appear to be defined in the code example provided, so none of your if's will match.
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();