Insert data to database not working (PHP-SQL) - php

My insert data sql command in my PHP code is not working. Can anyone help please?
I have a registration form that takes the values from the input fields (name, lastname, email, username and password)
The values that the user inputs in this fields should be saved into my table "users" whith columns (ID [which is the primary key /INT], name [TEXT], lastname[TEXT], e-mail [VARCHAR], username[VARCHAR] and password [VARCHAR]) .
Here is my current code:
if (isset ($_POST['name'],$_POST['lastname'],$_POST['email'],$_POST['username'], $_POST['password']))
{
//connect to database
$conn = mysqli_connect ('localhost', 'root', '', 'test_database');
if ($conn)
{
$sql="SELECT username FROM users WHERE username = '" . $_POST['username'] . "';";
$query = mysqli_query ($conn, $sql);
$result = mysqli_fetch_array ($query);
if ($result ['username'])
{
header ('Location: ' . $_SERVER['PHP_SELF'] . '?errno=1');
}
else
{
$sql="INSERT INTO users (ID, name, lastname, e-mail, username, password) VALUES (' ','" .$_POST['name'] . "' ,'" . $_POST['lastname']. "' ,'" . $_POST['email']. "' ,'" . $_POST['username']. "' ,'" . $_POST['password']. "');";
mysqli_query ($conn, $sql);
mysqli_close ($conn);
//registration completed, redirect to index page
//header ('Location:index.php?reg=1');
}
}
else
{
echo 'connection error';
}
}

Besides what has already been outlined in comments for the space VALUES (' ', for the ID column etc., your email column name contains a hyphen and is interpreted as e MINUS mail and as a mathematical operation.
Either rename it to e_mail or place ticks around it.
`e-mail`
Read the following on Identifier Qualifiers:
http://dev.mysql.com/doc/refman/5.7/en/identifier-qualifiers.html
Having used mysqli_error($conn) on the query would have thrown you a syntax error.
Sidenote: You should be escaping your data for quite a few reasons, one is for protection against an SQL injection and if your data could contain characters that MySQL could complain about such as John's Bar & Grill as an example.
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements.
Passwords
I also noticed that you may be storing passwords in plain text. This is not recommended.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP
Important sidenote about column length:
If and when you do decide to use password_hash() or crypt, it is important to note that if your present password column's length is anything lower than 60, it will need to be changed to that (or higher). The manual suggests a length of 255.
You will need to ALTER your column's length and start over with a new hash in order for it to take effect. Otherwise, MySQL will fail silently.

you use ' ' to insert id. the id should be autoincrement and unique. you cannot insert a white space to all.
try to remove id from insert into query. turn your query into this
$sql="INSERT INTO users (name, lastname, e-mail, username, password) VALUES ('" .$_POST['name'] . "' ,'" . $_POST['lastname']. "' ,'" . $_POST['email']. "' ,'" . $_POST['username']. "' ,'" . $_POST['password']. "');";

Related

Trouble specifying my tablename inside query because of dot notation

I'm having trouble specifying my tablename inside the following query.
$sql = "INSERT INTO db269193_crud.posts (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
The tablename is: db269193_crud.posts. I can't specify the table name as 'posts' because of my hostingprovider. They only allow me to specify it in conjunction with my databasename (which is db269193).
So the table name becomes: db269193(dot)posts. This dot however keeps lighting up in my editor as an incorrect syntax.
I need someone's help to tell me if I specified the table name correctly or if I have to use a variable to hide the dot notation like:
$tablename = 'db269193.crud';
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
You can put the entire name in backticks to escape it:
INSERT INTO `db269193_crud.posts` (post_title, description)
VALUES ('" . $title . "', '" . $description . "')
As for the rest of your statement, I would encourage you to use parameters instead of munging the query string. By putting random strings in the query, you are just inviting syntax errors and SQL injection attacks.
I can't specify the table name as 'posts' because of my hostingprovider. They only allow me to specify it in conjunction with my databasename (which is db269193).
I pretty much doubt that as it would require DB changes which simply make no sense. I assume that it's your fault as you did not select DB to use in the first place. Check how you connect and ensure you provide DB name as well or at least you mysqli_select_db() or equivalent.
$tablename = 'db269193.crud';
You can use backticks when name of table or column conflicts or is reserved word:
$tablename = '`db269193.crud`';
or
$tablename = '`db269193`.`crud`';
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
You are complicating simple strings with unnecessary concatentation. This will work and is less error prone:
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('{$title}','{$description}')";
however you are still seem to be vulnerable to sql injection here. I'd recommend switching to PDO.

PHP Code executing but not inserting data?

I've followed a year old online tutorial of Unity Client - PHP Server - Database integration. The code seems to execute fine, it reaches the 'echo"Success"' line etc perfectly.
However when I look at my database, there is nothing there. Its blank, and I have no idea why.
Note: The online tutorial used mysql... whereas I'm using the (non-depracted) mysqli... but there didn't seem to be that much of a difference, but I'm a total rookie at PHP coding, only having minimal experience at it so it is very possible I'm wrong?
<?php
/**
* Created by PhpStorm.
* User: Josh
* Date: 09/04/2016
* Time: 14:11
*/
$Username = $_REQUEST["Username"];
$Password = $_REQUEST["Password"];
$Hostname = "localhost";
$DBName = "statemilitaryrpdb";
$User = "root";
$PasswordP = "";
$link = mysqli_connect($Hostname, $User, $PasswordP, $DBName) or die ("Can't Connect to DB");
if (!$Username || !$Password) {
echo "Empty";
} else
{
$SQL = "SELECT * FROM accounts WHERE Username = '" . $Username ."'";
$Result = #mysqli_query($link, $SQL) or die ("DB ERROR");
$Total = mysqli_num_rows($Result);
if($Total == 0)
{
$insert = "INSERT INTO 'accounts' ('Username', 'Password') VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)";
$SQL1 = mysqli_query($link, $insert);
$Result2 = #mysqli_query($link, $SQL) or die ("DB ERROR");
echo(mysqli_num_rows($Result2));
}
else
{
echo"Username Already Used";
}
}
mysqli_close($link);
$insert = "INSERT INTO 'accounts' ('Username', 'Password') VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)";
Answer: Username and Password are the fields but you are trying to insert Username, Password and 0
Suggestion: Do more than just MD5 encryption, that is SUPER easy to decrypt.
Edit:
Also like #andrewsi said in the comments if your only going to check if its empty, than anyone could SQL inject your database and drop your tables or make changes. Make sure that you are filtering your inputs correctly.
Firstly, your query have only 2 columns, but you are inserting 3 values:
$insert = "INSERT INTO 'accounts' ('Username', 'Password') VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)";
Columns
Username
Password
Values to insert
$Username
md5($Password)
0
Thus, not all the values will be inserted.
Secondly, for MySQL related names, you need to use back ticks instead of single-quote.
Thus, this:
INSERT INTO 'accounts'
Should be:
INSERT INTO `accounts`
Thirdly, your code is vulnerable to MySQL Injection, you should prevent it using mysqli_real_escape_string():
$Username = mysqli_real_escape_string($link, $_REQUEST["Username"]);
$Password = mysqli_real_escape_string($link, $_REQUEST["Password"]);
Tip: You shouldn't suppress error messages:
#mysqli_query($link, $SQL)
Remove # to enable error reporting. It's very useful in diagnosing syntax errors.
Also, you shouldn't use md5() to hash passwords, as it's not very secure. Use password_hash and password_verify instead.
In debug mode, never use # to suppress errors, ie. #mysqli_query. Also or die("DB ERROR") isn't very descriptive. Even if that resolves, what good does DB ERROR provide you? Instead, use or die( mysqli_error($link) ) to see what's really going on with the query.
You also have 3 values to be inserted, but only 2 columns represented in the query statement:
('Username', 'Password') // 2 columns
VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)"; // 3 values
What column is 0 being inserted into? This value needs to be represented by a column.
And a table/column name should never be wrapped with quotes; only ticks `accounts`

MySQL PASSWORD () doesn't work with SELECT statement

The password function in mysql works fine with me in inserting and updating such as here:
$query_insert = "INSERT INTO `account`(`Gender`, `Birth_date`, `Name`, `UserName`, `Password`, `Email`, `Type`) VALUES ('" . $gender . "' , '" . $birthdate . "' , '" . $name . "' , '" . $username . "' , password('" . $password . "') , '" . $email . "' , 'Member' ) ";
it insert the hashed password correctly
but when i try to retrieve it in log in code it doesn't work !
mysqli_query($con, "SELECT * FROM account where UserName = '" . $username . "' AND password = password('" . $password . "') ");
I tried to use
mysqli_set_charset($con, 'utf8');
but the result is same
I even tried to use it in PHPMyAdmin as a select query, and the same error !
UPDATE
I used MD5()
and it worked with me !
As documented under PASSWORD():
Note
The PASSWORD() function is used by the authentication system in MySQL Server; you should not use it in your own applications. For that purpose, consider MD5() or SHA2() instead. Also see RFC 2195, section 2 (Challenge-Response Authentication Mechanism (CRAM)), for more information about handling passwords and authentication securely in your applications.
Also, if you're rolling your own authentication system (which I'd strongly discourage), you really should read both The definitive guide to form based website authentication and Secure hash and salt for PHP passwords.

I'm new to PHP and MySQL. I cannot figure this simple system out

<?php
$db = new mysqli("localhost","root","password","eme");
if($db->connect_errno){ echo "Not connected."; exit();}
echo $db->query("SELECT * FROM users") . "<br>";
echo $_POST[FirstName] . " " . $_POST[LastName];
$db->query("INSERT INTO users (FirstName, LastName) VALUES ('$_POST[FirstName]','$_POST[LastName]')");
echo $db->query("SELECT * FROM users") . "<br>";
?>
I cannot figure out why this code doesn't work. The only line that outputs anything is "echo $_POST[FirstName] . " " . $_POST[LastName];"
My database has a "users" table and the database is called eme. The database connects properly.
There is currently no data in the database. I figured I could add some with "INSERT," but it's failing.
You have several problems:
The query() method of mysqli returns a mysqli_result object. you need to use one of it's methods to get the actual data back from the query. For instance fetch_assoc()
In your insert, you need to either assign $_POST['FirstName'] to a variable, or explicitly add it to the string.
ie.
"INSERT INTO users (FirstName, LastName) VALUES ('" . $_POST['FirstName'] . "','" . $_POST['LastName'] . "')"
or
$first = $_POST['FirstName'];
$last = $_POST['LastName'];
"INSERT INTO users (FirstName, LastName) VALUES ('" . $first . "', '" . $last . "')"
You should also sanitize the data before inserting it to prevent major security threats.
Lastly, it's not a bug per se, but you should always use a string or integer value for an array index.
ie. You have $_POST[FirstName], it should be either $_POST['FirstName'] or $_POST["FirstName"]
It will still work, but the interpreter thinks it's a constant, which isn't defined, so assumes the literal value, throwing a warning (maybe notice, can't remember offhand). It's unnecessary overhead.
Try this...
$db->query("INSERT INTO users (FirstName, LastName) VALUES('".$_POST['FirstName']."','".$_POST['LastName']."')");
For more info on Quotes, look over this link - What is the difference between single-quoted and double-quoted strings in PHP?

{plain}password in Database and login error

I am coding a login panel to access to an Administration Panel.
The data (username and passw) are stored in a MySQL Database (type: InnoDB).
Looking in the tables the passwords are stored as plain and in the field password I have:
{plain}password.
Adapting a code that I already have, I have some problems because that {plain} thing is confusing me a bit.
My old code is:
// Construct SQL statement for query & execute
$sql = "SELECT * FROM table WHERE user = '" . $username . "' AND password = '" . md5($password) . "'";
$result = $mysqli->query($sql) or die(mysql_error());
So if I replace the "{plain}password" from the field in the database with an MD5 password, the code works great, but if I modify my code to the following one:
// Construct SQL statement for query & execute
$sql = "SELECT * FROM table WHERE user = '" . $username . "' AND password = '" . $password . "'";
$result = $mysqli->query($sql) or die(mysql_error());
I can't login because the password is wrong!
Any idea how to fix this?
If there is the prefix "{plain}" in front of the real password, you have to adjust your query to include that prefix.
$sql = "SELECT * FROM table WHERE user = '" . $username . "' AND password = '{plain}" . $password . "'";
$result = $mysqli->query($sql) or die($mysqli->error());
Also note that you should change mysql_error() in the die() command to use mysqli functions as well (so use $mysqli->error).
PS: You should have a look at how to store password nowadays. Storing them in plain text is not secure by any means.
EDIT
Mentioning the comment by #BrianRasmussen here as well:
Make sure $username and $password have been sanitzed before being used directly (using string concat) in a query! Otherwise your code is open to SQL injections of all sorts.
I don't know for sure what {plain} means, I guess it indicates that the password is in plain text - and this string is actually present. Hence, your second SQL should include it:
$sql = "SELECT * FROM table WHERE user = '" . mysql_real_escape_string($username) . "' AND password = '{plain}" . mysql_real_escape_string($password) . "'";
Note that I'm not starting the discussion about storing admin passwords in plain text, purely answering a technical question. However I must say that storing plain text passwords is a VERY bad idea.
Also note that I added mysql_real_escape_string to sanitise your input.

Categories