Inserting MD5 hashes into database using an array

I have a problem inserting passwords from a text file into a database using md5 hashes. It inputs everything else from the text file as it should but I don’t know how to get it to input unique hash values using the ‘Password’ fields from the text file. I know the problem is with the array and it is not done correctly, can anyone help me fix this?

[php]//insert from text file

$Password = $_POST[‘Password’];
$passwordmd5 = md5 ($Password);

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]’, ‘$passwordmd5’)”;
$milestone_query .= $i < $count ? ‘,’:’’;
$i++;
}
mysql_query($milestone_query) or die(mysql_error());
}
echo “Done!”;[/php]

You need to dump this obsolete code that has been removed from Php and use PDO and NEVER EVER use md5 for passwords. MD5 was cracked like 20 years ago.

You can download my PDO Bumpstart Database in my signature and study this tutorial:
https://phpdelusions.net/pdo

Thanks for the reply, but I don’t need it to be secure, I just need it to be done this way for some college work, this isn’t anything that will be used for anything else, so security wise it does not matter. Any idea how to make my code work this way?

So, you set a md5 hash on a single password at the top of the script, never hashing anything from the txt file, and you don’t know why you are getting the results you are. Perhaps you should ask the professor.

“I don’t need it to be secure” is one we have heard 1,000’s of times, and why websites are hacked by the millions every day. Security is always paramount. It doesn’t matter if you think you need it or not. It leads to bad coding practices. Even accepting work with obsolete code is a sign that you need to look for a new university.

Yes, you could get this code to work, but even walking you through it would be a huge injustice to you. I suggest Kevin’s tutorial on PDO, but you could use MySQLi also, fully documented in the manual @, surprisingly, php.net.

You should not be using MD5() as already stated, rather use password_hash() and password_verify(). Learning this now, will help you later. Learning proper coding standards are not something you should put off until after this project. As getting this project to just work, will lead to just getting the next project to work. Leaving you in a never ending downward spiral into bad coding. Eventually ending up with a glob of mess that you yourself can’t even understand, much less anyone else.

Okay I’ve changed it to not use MD5.

These are the errors I have now:

  1. Notice: Undefined variable: PDO in C:\wamp\www\createTable.php on line 34
  2. Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\createTable.php on line 34

How do I make the PDO work?

Here’s my new code:

[php]//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 (?, ?, ?, ?, ?)’);
$query->bindParam(1,$PDO);
foreach($file as $row) {
$milestone = explode(’;’,$row);
$milestone[4] = password_hash($milestone[4], PASSWORD_DEFAULT);
$query->execute($milestone);
}[/php]

PHP is case sensitive, you initialize the variable as $pdo but later use it as $PDO

Plus after looking over your query I am 99.9 percent sure it isn’t going to work after you get the other bugs ironed out.

Against my better judgement I took some of my old code and converted to what you are trying to do. ::slight_smile:

Here’s the script:

[php]<?php

$pdo = $myPDO();

$sql = 'INSERT INTO tbl_User (FName, LName, Email, Password) VALUES ';

foreach ($file as $records) {

$record = explode(";", $records);

$query[] = '(:fname' . $n . ', :lname' . $n . ', :email' . $n . ', :password' . $n . ')';


$iData['fname' . $n] = $record[1];
$iData['lname' . $n] = $record[2];
$iData['email' . $n] = $record[3];
$password = password_hash($record[4], PASSWORD_DEFAULT);
$iData['password' . $n] = $password;

$n += 1;

}

if (!empty($query)) {
$sql .= implode(’, ', $query);
$stmt = $pdo->prepare($sql);
$result = $stmt->execute($iData);
}[/php]

First, I can’t promise you anything with this script for it’s untested, secode in your mysql the id should be your primary key and auto incremented, so you don’t have to insert the id, thirdly I would learn variable naming better (I have to admit my variable naming sometimes isn’t the greatest).

Lastly I was going to introduce:
[php]try {

} catch (Exception $exc) {
echo $exc->getTraceAsString();
}[/php]

but I think that would be overloading it a bit. :wink:

Thanks for the help. I’ve used your code but when I use “$pdo = $myPDO();” it gives me the error on that line: Notice: Undefined variable: myPDO in C:\wamp\www\a1\createTable.php on line 33 but if I remove the $ from myPDO it works. That is fixed, however, I get the error: Fatal error: Function name must be a string in C:\wamp\www\a1\createTable.php on line 33 for the line of code? I’m not sure what to put as a string?

[php]
$host = ‘localhost’;
$dbname = ‘test’;
$pdo = myPDO(‘mysql:host=$host;dbname=$dbname’, ‘C:\wamp\www\a1’);
$file = file(‘userData.txt’);
$sql = 'INSERT INTO tbl_User (FName, LName, Email, Password) VALUES ';

foreach ($file as $records) {

  $record = explode(";", $records);
 
 $query[] = '(:FName' . $n . ', :LName' . $n . ', :Email' . $n . ', :Password' . $n . ')';


 $iData['FName' . $n] = $record[1];
 $iData['LName' . $n] = $record[2];
 $iData['Email' . $n] = $record[3];
 $password = password_hash($record[4], PASSWORD_DEFAULT);
 $iData['Password' . $n] = $password;

 $n += 1;

}

if (!empty($query)) {
$sql .= implode(’, ', $query);
$stmt = $pdo->prepare($sql);
$result = $stmt->execute($iData);
}

try {

} catch (Exception $exc) {
echo $exc->getTraceAsString();
}[/php]

I’m unable to edit my last post, sorry for making a new one.

After changing the code from $pdo = myPDO(‘mysql:host=$host;dbname=$dbname’, ‘C:\wamp\www\a1’,’’); to

$pdo = new myPDO(‘mysql:host=$host;dbname=$dbname’, ‘C:\wamp\www\a1’,’’);

I get this error: Fatal error: Class ‘myPDO’ not found in C:\wamp\www\a1\createTable.php on line 34

Every time I fix something I get another issue. I’m using wamp server, do I need additional drivers to make this work? If so, please link me to what I need.

Get rid of the my in myPDO. Striders connection is setup different. Below is how it is supposed to be.

$pdo = new PDO(‘mysql:host=$host;dbname=$dbname’, ‘C:\wamp\www\a1’,’’);

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 “,”

Sponsor our Newsletter | Privacy Policy | Terms of Service