Inserting MD5 hashes into database using an array

It seems that the only way I am able to get everything to insert into the database is by using my old code, the only thing that it doesn’t do is insert the hash value for each password. Is there a way to make it insert the hash value by using the code below? It inserts each password as it is but how do I make it insert as a hash value?

[php]//insert from text file

if(isset($_POST[‘ID’]))
{
$ID = $_POST[‘ID’];
}
if(isset($_POST[‘FName’]))
{
$FName = $_POST[‘FName’];
}
if(isset($_POST[‘LName’]))
{
$LName = $_POST[‘LName’];
}
if(isset($_POST[‘Email’]))
{
$Email = $_POST[‘Email’];
}

if(isset($_POST[‘Password’]))
{
$Password = $_POST[‘Password’];
$Password = password_hash;

}

mysql_select_db(“test”) or die (“Unable to select database!”);
$file = file(‘C:\wamp\www\a1\userData.txt’); # read file into array
$count = count($file);
if($count > 0) # file is not empty
{
$milestone_query = “INSERT into tbl_User(ID, FName, LName, Email, Password) values”;
$i = 1;
foreach($file as $row)
{
$milestone = explode(’;’,$row);
$milestone_query .= “(’$milestone[0]’, ‘$milestone[1]’, ‘$milestone[2]’, ‘$milestone[3]’, ‘$milestone[4]’)”;
$milestone_query .= $i < $count ? ‘,’:’’;
$i++;
}
mysql_query($milestone_query) or die(mysql_error());
}
echo “Done!”;[/php]

For gawd sake, throw that code away! I gave you a good tutorial to get you going. It appears you didn’t take the time to learn it.

the only thing that it doesn't do is insert the hash value for each password
My guess would be the length you set for the column or it's data type.

I managed to make it work 100% using the PDO method, thanks everyone for your input!

After making it insert all the hashes into the database, I made a login form which is supposed to use the original FName and Password to log into the system. I have an issue with the password field, if I insert the original password, it does not work, but if I enter the hash that it generated then it is successful. I’ve altered the code to make it change the string entered into a hash so that it matches the one in the database but it does not work.

Can anyone tell me what I did wrong or help me correct the code?
[php]
include ‘DBConn.php’;
mysql_select_db(“test”) or die (“Unable to select database!”);
if(isset($_POST[‘FName’])){ $FName = $_POST[‘FName’]; }
if(isset($_POST[‘Password’])){ $Password = password_hash($Password = $_POST[‘Password’]); }

	if( empty($FName) || empty($Password) )
		echo "Username and Password Mandatory - from PHP";
	else
	{

$sql = "SELECT count(*) FROM tbl_User where(
	        FName='$FName' 
			AND 
			Password='$Password')";
			
	$res = mysql_query($sql);
	$row = mysql_fetch_array($res);

	if( $row[0] > 0 )
	 echo "Login Successful";
	else
	 echo $sql;
	}	[/php]

Here’s the PDO code for reference:
//insert from text file

$host = ‘localhost’;
$dbname = ‘test’;
$PDO = new PDO(“mysql:dbname=$dbname; host=$host”);
$file = file(‘userData.txt’);
$query = $PDO->prepare(‘INSERT into tbl_User(ID, FName, LName, Email, Password) values (?, ?, ?, ?, ?)’);

foreach($file as $row) {
$milestone = explode(’;’,$row);
$milestone[4] = password_hash($milestone[4], PASSWORD_DEFAULT);
$query->execute($milestone);
}

echo “Done!”;

mysqli_close($DBConnect);
?>

You have a PDO version. Use that and forget about the other. Focus solely on making the PDO version work correctly.

What [member=72272]astonecipher[/member] said. No “real” programmer should even help you with that very bad old code. Look up how to use password_hash and password_verify. It is not complicated.

You do not have a consistent naming convention. Get in the habit of using all lowercase and separating_words_with_an_underscore.

You also mixed mysqli with the PDO and I am not so sure about that foreach on your insert. That would say you are inserting more than one record at a time which I dont think you are doing.

From here on out, the almighty coding gods forbid you to post that obsolete code. PDO is your friend and we are your friends. Obsolete code is of the devil!

Here is code from one of my join pages. Pull from it what you will.

[php]<?php
/*

  • Add Data
  • Last Modified 4/3/2016 6:14 PM
    */

require(’./config.php’);

//----------------------------------------------------------------------------
// Allow direct access to this page
//----------------------------------------------------------------------------

define(‘securepage’, true);

//----------------------------------------------------------------------------
// Page Header
//----------------------------------------------------------------------------

require(’./includes/header.php’);

//----------------------------------------------------------------------------
//
//----------------------------------------------------------------------------

$show_error = false;

if ($_POST)
{
//------------------------------------------------------------------------
// Trim Data, Check Missing Fields
//------------------------------------------------------------------------

include('./includes/validate_registration.php');

//------------------------------------------------------------------------
// Check for errors
//------------------------------------------------------------------------

if ($error)
    {
    $show_error = true;
    }
else
    {
    // generate 16 random bytes
    $raw_token = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);

    // encode the random bytes and send the result to the user
    $encoded_token = bin2hex($raw_token);

    // hash the random bytes and store this hash in the database
    $token_hash = hash('sha256', $raw_token);

    $hashed_password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $sql             = "INSERT INTO users (email, password, activation_key) values(?,?,?)";
    $stmt            = $pdo->prepare($sql);
    $stmt->execute(array(
        $_POST['email'],
        $hashed_password,
        $token_hash
    ));

    $msg            = 'activate';
    $activation_msg = "Activation Link $url_website/activate.php?k=$encoded_token";
    if (@!mail("{$_POST['email']}", "Activation Information", $activation_msg, "From: $email_from\r\n"))
        {
        /* error_get_last() Array
         * [type] => 2
         * [message] => mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()
         * [file] => E:\Zend\Apache2\htdocs\projects\mysite\join.php
         * [line] => 60
         */
        $error = error_get_last();
        // If no mail server, log the failed mail error
        if (LOG_ERROR == 1)
            {
            error_log("$mysql_datetime|{$error['message']} File: {$error['file']} Line: {$error['line']}\r\n", 3, "$errorlog_path");
            } //LOG_ERROR == 1

        die("There was a problem sending activation email. Please contact support.");
        }

    die(header("Location: login.php?activate"));

    } // End Else
} // End POST

//--------------------------------------------------------------------
// Display Logo
//--------------------------------------------------------------------

logo();

//--------------------------------------------------------------------
// Display Form Errors
//--------------------------------------------------------------------

if ($show_error)
{
show_form_errors($error);
}

//--------------------------------------------------------------------
// Display Form
//--------------------------------------------------------------------

?>

Email *
Password *
Confirm Password *
<?php include('./includes/footer.php'); ?>[/php]

Thank you for the help!

If I add more fields to my sql select statement, to make it verify if all these fields listed below are true, it doesn’t work, but if I only use FName and Password it works, I’m curious to know why it doesn’t let me go through when I add more fields to verify? I’ve made the changes to the login screen to cater for these other fields, but how come it doesn’t work when I make it verify more than just those two fields?

$sql = “SELECT count(*) FROM tbl_User where(
FName=’$FName’,
LName=’$LName’,
Email=’$Email’
AND
Password=’$Password’)”;

EDIT I fixed it by adding “AND” after each one instead of using “,”

Not sure what your doing, but your doing it wrong. What is the overall task at hand, not the code you are trying to do what you think needs to be done.

Basically what I was required to do was insert values into a database using a textfile, implement code that changes the passwords into hashes, then after all of that is complete, make a log in screen using the data from the database to log in. I’ve sorted this out now. Thanks everyone for their input.

Is this for school?

insert values into a database using a textfile

You are never going to do this in the real world. If you needed to import numerous records from a text file, doing it with code is the LAST way it would be done.

It’s for college. I know it will never be used in the real world, that’s why I had to follow the requirements in the question paper and make it work that way instead of following everything from online. It’s stupid, but I’m not going to lose marks over that, that’s why I made sure I got it to work according to the requirements of the question paper.

It seems every time someone comes with school work, the teachers are teaching wrong. Unbelievable!

It’s usually the people who set the exam papers and assignment papers that have no idea what they’re doing. They’re just lazy and don’t prepare us for the real world. That’s the education system though, unfortunately.

I disagree with that statement. We have an ETL developer that his only job is to programmatically import records stored in files to databases.

Most programming courses in general are out dated. Even though this industry changes quickly, the curriculum is slow to change, partly due to the requirements to make a change. Take windows development. MOST colleges teach VB.NET as a required language. However, they still teach Windows Forms and not WPF. Windows forms were last an industry standard 15- 20 years ago.

We have an ETL developer that his only job is to programmatically import records stored in files to databases.

Really? Does he not know how to use mysql import or any of the many mysql gui’s to right click/import? He really keeps writing scripts to do it?

That is a really limited view actually. One there are more RDBMS’s than just MySQL. Two, the process normally ends up being automated. You also have to account for the myriad of formats that different senders will be using.

Since it appears you are unfamiliar with the position, ETL Developer

I should probably correct my assertion. Since I have never worked for another company but my own, I should say in my experience…

I actually have no idea what goes on in company’s.

Just learned something new, ETL, and as it turns out, I am going to need an ETL guy for the project I am working on right now. They have a really old poorly designed database that I am creating a new app/db from the ground up.

Since their existing db is so wrong, I have to completely ignore they have it and design a correct db. Doing the data migration is going to be a biotch.

I see there are various ETL software’s. Anybody ever use one? One of those listed on the Wiki may be just what I need.

Sponsor our Newsletter | Privacy Policy | Terms of Service