Jump to content

Php doubt


suvin_prathab

Recommended Posts

 

Duplicate entry '' for key 1

 

This is ma problem i hve created a login page ..if i give a on pair of username and a password it inserts a empty row in table in the Database and then only in the 2nd row the given username and password in inserted.. i not able to rectify it.. please some onle tell me ... ill give the whole code of that login page.. it is below..

 

<!--CONNECTING TO THE DATABASE-->

<?php

//ERROR REPORTING AND DISABLING NOTICES

error_reporting(E_ALL & ~E_NOTICE); 

 

$connection = mysql_connect("localhost","root","suvin");

if(!$connection){

die("Database Connection Failed !".mysql_error());

}

?>

<!--SELECTING THE DATABASE LOGIN-->

<?php

$db_select = mysql_select_db("guest_book",$connection);

if(!$db_select){

die("Database Selection Failed !".mysql_error());

}

 

?>

 

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Fight Club</title>

</head>

 

<body bgcolor="#A4DA50">

 

<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">

<input type="text" name="txt_username" /><br /><br />

<input type="password" name="txt_password" /><br /><br />

<input type="submit" name="btn_login" value="Login"  />

<input type="button" name="btn_cancel" value="Cancel" />

</form>

 

<!--WRITING TO THE DATABASE-->

<?php

$username = $_POST["txt_username"];

$password = $_POST["txt_password"];

$query1 = "INSERT INTO login (username,password) VALUES ('$username','$password')";

mysql_query($query1,$connection) or die(mysql_error());

?>

 

 

</body>

</html>

<!--CLOSE DATABASE CONNECTION-->

<?php

mysql_close($connection);

?>

Link to comment
https://forums.phpfreaks.com/topic/122524-php-doubt/
Share on other sites

You should check first if the form is submitted, as the query will run every time the page is accessed, not every time the form is submitted. Change the "Writing to the database part" to:

 

<?php
if(isset($_POST['txt_username'])){
     $username = mysql_real_escape_string(htmlentities($_POST["txt_username"])); //clean the data
     $password = $_POST["txt_password"];
     $query1 = "INSERT INTO login (username, password) VALUES ('$username', '$password')";
     mysql_query($query1, $connection) or die(mysql_error());
}
?>

 

The password should be hashed so that you don't run the risk of attackers getting your users passwords.

Link to comment
https://forums.phpfreaks.com/topic/122524-php-doubt/#findComment-632662
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.