user3125898
user3125898

Reputation: 57

Adding ID number to database PHP

This script hashes a list of words with MD5 and stores it in the database along with its plain text:

<?php
    $dict = $_POST["dict"];
if (!isset($_POST['submit'])){
    echo "<form method=\"post\" action=\"\">";
    echo "Wordlist: <input type=\"text\" name=\"dict\"><br>";
    echo "<input type=\"submit\" value=\"GET DIC\" name=\"submit\">";
    echo "</form>";
}else{
    $file = fopen($dict, "r");
    while (!feof ($file)){
    $load[$i] = fgets($file, 1024);
    mysql_connect("xxx","xxx","xxx");
    mysql_select_db("xxx");
    $word = $load[$i];
    $md5 = md5($word);
    $lastid=mysql_insert_id();
    $lastid=$lastid+1;
    mysql_query("INSERT INTO md5 VALUES ('$lastid', '$md5', '$word');");
    $i++;
    $limit = count($load);
    $width2 = $limit;
}
    fclose($file);
    echo "[+]Loaded ".$limit." word.";
    echo "<br>Done.";
}
?>

I'm having troubles generating the ID for each row. I want the script to begin the number of ID from the last number that is stored in the database.

for example:

ID : MD5 : Country
1  : HASH: Africa
2  : HASH: Russia

When I execute the script I want it to start from ID number 3 and carries on until the list is finished. What's wrong with my script?

Upvotes: 0

Views: 299

Answers (3)

Irek Kubicki
Irek Kubicki

Reputation: 57

Consider using prepared statements (with mysqli or PDO). Otherwise you will get into trouble if any word will contain an apostrophe. Additionally, mysql_ functions are deprecated and will be removed in future.

Upvotes: 0

Humphrey
Humphrey

Reputation: 2817

I would suguest that you use auto incremement that will save you a lot of lime. Because Auto increment starts to add from the previous number as you said that it will be 3.

Upvotes: 1

Jelle Ferwerda
Jelle Ferwerda

Reputation: 1229

In your table, set the ID field to autoincrement. Then remove the whole ID section from your code, and let the database handle it

delete: $lastid=mysql_insert_id();

Delete: $lastid=$lastid+1;

Change to: mysql_query("INSERT INTO md5 (md5, country) VALUES ( '$md5', '$word');");

Delete: $i++;

Upvotes: 4

Related Questions