This is my PHP form which I have been using for login but i belive it is insecure. Can someone aid me in converting this to a PDO version to be more secure, I am having great difficulty. Form: <form id="form1" name="form1" method="post" action="test.php"> <label>Name <input type="text" name="textfield" /> </label> <p> <label> <input type="submit" name="Submit" value="Submit" /> </label> </p> </form> Code (markup): PHP Script (test.php): <?php $host=""; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name=""; // Database name $tbl_name="members"; // Table name mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $username = $_POST['textfield']; echo '</br>'; $query = mysql_query("SELECT * FROM `members` WHERE `username`='$username'"); while($result = mysql_fetch_array($query)) { //display echo $result['DOB']; echo $result['email']; } ?> Code (markup): Thank you in advance
Try this: <?php $db = new PDO('mysql:host='.$host. ';dbname='.$db_name. ';charset=UTF-8', $username, $password); $stmt = $db->prepare('SELECT * FROM `members` WHERE `username`=:username LIMIT 1'); $stmt->bindValue(':username', $_POST['textfield'], PDO::PARAM_STR); $stmt->execute(); $result = $stmt->fetchObject(); print_r($result); ?> PHP:
Your PHP code is fully clean except the MySQL query. $query = mysql_query("SELECT * FROM `members` WHERE `username`='" . mysql_real_escape_string($username) . "'"); PHP:
Oh i rather should do a real check if the username is valid. Normaly username contains a-zA-Z0-9 en sometimes -_ and other signs... use preg_match to validate your input and then you can even use the deprecated mysql functions.. Don't think PDO is the solution to bad input validation!
thanks for your reply. can you confirm the above is correct. How does your code now to display the 'DOB' and 'email' result field?
Try this code... <?php $db = new PDO('mysql:host='.$host. ';dbname='.$db_name. ';charset=UTF-8', $username, $password); $stmt = $db->prepare('SELECT * FROM `members` WHERE `username`=:username LIMIT 1'); $stmt->bindValue(':username', $_POST['textfield'], PDO::PARAM_STR); $stmt->execute(); $result = $stmt->fetchObject(); print_r($result); ?> PHP:
For making secure connection or encryption you can even use ssl and try to use session for the securities