I have a question about my code. The problem is that when i say echo $collumB than he shows the student_city. that is in my database but i want that it shows the decrypted password. It just shows the wrong data
(there is an another page where i encrypt the password but i need the decrypted password echo'ed
<html>
<head>
<title>insert data in database using PDO(php data object)</title>
<link rel="stylesheet" type="text/css" href="style-login.css">
</head>
<body>
<div id="main">
<h1>Login using PDO</h1>
<div id="login">
<h2>Login</h2>
<hr/>
<form action="" method="post">
<label>Email :</label>
<input type="email" name="stu_email" id="email" required="required" placeholder="john123#gmail.com"/><br/><br />
<label>Password :</label>
<input type="password" name="stu_ww" id="ww" required="required" placeholder="Please Enter Your Password"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
</div>
<?php
//require ("encrypt.php");
if(isset($_POST["submit"])){
$hostname='localhost';
$username='root';
$password='';
$pdo = "college";
$student_email = $_POST["stu_email"];
$encrypt_key = "4ldetn43t4aed0ho10smhd1l";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=college","root","$password");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Query
$statement = $dbh->prepare("SELECT student_email, student_city, AES_DECRYPT(student_password, '$encrypt_key')
AS student_password FROM students WHERE student_email = :student_email ORDER BY student_email ASC");
// Assign and execute query
$statement->bindParam(':student_email', $student_email, PDO::PARAM_STR);
$statement->setFetchMode(PDO::FETCH_ASSOC);
$statement->execute();
// Get data
while($row = $statement->fetch()) {
echo "1 ,";
//$columnA_value = $row['student_city'];
$columnB_value = $row['student_password'];
}
echo "2 ,";
echo $columnB_value;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
?>
</body>
</html>
SELECT student_email, student_city, CAST(AES_DECRYPT(student_password, '$encrypt_key') AS char(50)) AS student_password FROM students WHERE student_email = :student_email ORDER BY student_email ASC;
Try to explicitly cast it to string. You can change the '50' according to your requirement.
Also your echo is outside while loop, hence it will print only last record if there are more than 1 records.
Related
I have two tables, members and games. In members is data such as member_id, first_name, last_name, etc.
What I'm trying to do is create a form for games, where the user can input the first and last names of the member who participated (in one string, not separately) and some PHP code queries this name, finds the corresponding id and stores this instead. Of course, member_id is a foreign key in games, but the users aren't going to know the member's id, they will only know their name.
If anyone could explain how I might go about doing this I would greatly appreciate it.
Form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form</title>
</head>
<body>
<form action="action.php" method="post">
<p>
<label for="date">Date:</label>
<input type="date" name="date" id="date">
</p>
<p>
<label for="duration">Duration:</label>
<input type="time" name="duration" id="duration">
</p>
<p>
<label for="member_id">Member Name:</label>
<input type="text" name="member_id" id="member_id">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
Action:
<?php
// database connection
include 'pdo_config.php';
try {
// new pdo connection
$conn = new PDO($dsn, $user, $pass, $opt);
// prepare statement and bind parameters
$stmt = $conn->prepare("INSERT INTO games (date, duration, member_id)
VALUES (:date, :duration, :member_id)");
$stmt->bindParam(':date', $date);
$stmt->bindParam(':duration', $duration);
$stmt->bindParam(':member_id', $member_id);
// post data
$date = $_POST['date'];
$duration = $_POST['duration'];
$member_id = $_POST['member_id'];
// execute statement
$stmt->execute();
// success or error message
echo "New record created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
This should work.
Ask the user to input the member name in the form instead of the member id. Then make a first query to the database to get the member id from the member name.
Have in mind that it's not a good idea to search the member id from its name, because you could have more than one member whit the same name.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form</title>
</head>
<body>
<form action="action.php" method="post">
<p>
<label for="date">Date:</label>
<input type="date" name="date" id="date">
</p>
<p>
<label for="duration">Duration:</label>
<input type="time" name="duration" id="duration">
</p>
<p>
<label for="member_name">Member Name:</label>
<input type="text" name="member_name" id="member_name">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
// database connection
include 'pdo_config.php';
try {
// new pdo connection
$conn = new PDO($dsn, $user, $pass, $opt);
// post data
$date = $_POST['date'];
$duration = $_POST['duration'];
// Note that the explode only works well if user inputs one blank space to separate the name
// You can try to improve the separation method or better use two different inputs in the form
$nameArray = explode(" ", $_POST['member_name']);
$first_name = $nameArray[0];
$last_name = $nameArray[1];
$statement = $conn->prepare("SELECT member_id FROM members WHERE first_name = :first_name AND last_name = :last_name");
$statement->execute(array(':fisrt_name' => $first_name, ':last_name' => $last_name));
$row = $statement->fetch();
$member_id = $row['member_id'];
// prepare statement and bind parameters
$stmt = $conn->prepare("INSERT INTO games (date, duration, member_id)
VALUES (:date, :duration, :member_id)");
$stmt->bindParam(':date', $date);
$stmt->bindParam(':duration', $duration);
$stmt->bindParam(':member_id', $member_id);
// execute statement
$stmt->execute();
// success or error message
echo "New record created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
This is my PHP code.
<html><head>
<title>login.php</title>
<link rel = "stylesheet" href="login-style.css">
</head>
<body>
<div class = "container">
<div class = "message">
<?php
define('DB_NAME','mydb');
define('DB_USER','root');
define('DB_PASSWORD','');
define('DB_HOST','127.0.0.1');
$link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if($link){
die('could not connect:'. mysql_error());
}
$db_selected = mysql_select_db(DB_NAME,$link);
if(!$db_selected){
die('can\'t use'.DB_NAME . ': ' . mysql_error());
}
$value1 = $_POST['name'];
$value2 = $_POST['password'];
$sql = "INSERT INTO Account (username,password) VALUES ('$value1','$value2')";
if(!mysql_query($sql))
{die('ERROR'.mysql_error());
}
mysql_close();
?>
<h1>Thank you for logging in </h1>
<form action = "form.html">
<p class ="submit">
<button type ="submit" >
GO TO FORM
</button>
</p>
</div>
</div>
</body>
</html>
I want to store the data in MySQL but when I run the html code (which i have connected to this php code using action =" name of this file"), no entry is done in database I created, can you tell me what is done wrong and help me to correct it?
<DOCTYPE! html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>Sign-In</title>
<link rel = "stylesheet" href ="style-sign.css">
<script type = "text/javascript">
function validateForm(){
var x = document.forms["forma"]["login"].value;
if(x == null || x == "")
{ alert("fill the field ");
return false;
}
var y = document.forms["forma"]["password"].value;
if( y == null || y == "")
{
alert("fill the field");
return false;
}
}
</script>
</head>
<body >
<div class="container">
<div class="login">
<h1>Login</h1>
<form name = "forma" method="post" onsubmit="return validateForm()" action = "login.php">
<p>
<input type="text" name="name" value="" placeholder="Username or Email">
</p>
<p>
<input type="password" name="password" value="" placeholder="Password">
</p>
<p class="submit">
<input type="submit" name="commit" value="Login" >
</p>
</form>
</div>
</div>
</body>
</html>
this is my html code which i have connected to this php file ,I am using xampp and using phpmyadmin , I am not getting any error and apache and mysql both are running
help me with this problem
Change the following:
$sql = "INSERT INTO Account (username,password) VALUES ('$value1','$value2')";
To:
$sql = "INSERT INTO Account (username,password) VALUES ($value1,$value2)";
EDIT:
You do not have input fields setup for the username and password. So POST will not work.
First you From needs an action and a method.
Best woould be to rename the file to form.php
<form action = "form.php" method="POST">
in the result file ...
Connect to the database
$mysqli= #new mysqli('localhost', 'fake_user', 'my_password', 'my_db');
if ($mysqli->connect_errno) {
die('Connect Error: ' . $mysqli->connect_errno);
}
escape your value strings
$query= "INSERT INTO Account (username,password) VALUES ('".$mysqli->real_escape_string($value1)."','".$mysqli->real_escape_string($value2)."')"
Execute query
$result=$mysqli->query($query);
Verify results if any or check if an Error occured
if(!$result) {
$ErrMessage = $mysqli->error . "\n";
$mysqli->close();
die( $ErrMessage) ;
}
This might be a silly question but I am trying to call the same query to two different pages but once I call the second time, the link to the page would not work anymore. The way I have it setup at the moment is that all the pages in the app are on one file (index.php). I am linking to each page by using id (href="#page2"). If I call the same query, depending on the order of pages, only the "top" page, or in this case, Page 1 will work. I tried changing the variable names so that it would treat it as a different call but to no avail.
I am developing this app using Phonegap Build and it would be really helpful if ANYBODY can help.
Page 1
<div data-role="page" id="page1">
<form action="post-comment.php" method="POST">
<h3>COMMENT</h3>
<input type="text" name="name" placeholder="Name"><br />
<textarea name="comment" cols="50" rows="2" placeholder="Enter Comment"></textarea><br />
<input type="submit" value="comment" onClick="javascript.ajax_post()"></input><br />
</form>
<?php
$find_comments = mysql_query("SELECT * FROM COMMENTS");
while($row = mysql_fetch_assoc($find_comments))
{
$comment_name = $row['name'];
$comment = $row['comment'];
echo "$comment_name - $comment<br />" ;
}
?>
</div>
Page 2
<div data-role="page" id="page2">
<?php
$find_comments1 = mysql_query("SELECT * FROM COMMENTS");
while($row = mysql_fetch_assoc($find_comments1))
{
$comment_name1 = $row['name'];
$comment1 = $row['comment'];
echo "$comment_name1 - $comment1<br />" ;
}
?>
</div>
I suggest using PDO - DOC instead of mysql, I would do it this way :
Connect to your database :
$hostdb = "your_host";
$namedb = "db_name";
$userdb = "user_name";
$passdb = "pass";
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);
try {
$db = new PDO("mysql:host=$hostdb; dbname=$namedb; charset=utf8", $userdb, $passdb, $options);
return $db;
} catch (PDOException $e) {
$err = "DB Connection Error, because: ". $e->getMessage();
print $err;
}
Now you can use $db to connect to your database in your script and fetch comments :
<div data-role="page" id="page1">
<form action="post-comment.php" method="POST">
<h3>COMMENT</h3>
<input type="text" name="name" placeholder="Name"><br />
<textarea name="comment" cols="50" rows="2" placeholder="Enter Comment"></textarea><br />
<input type="submit" value="comment" onClick="javascript.ajax_post()"></input><br />
</form>
<?php
$find_comments ="SELECT * FROM COMMENTS";
$stmt = $db->prepare($find_comments);
if(!$stmt->execute()){
print "error";
} else {
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($comments as $comment) {
echo $comment['name']."</br>";
echo $comment['comment'] ;
}
$stmt->closeCursor(); // Close connection
}
?>
</div>
then in your Page2 just do the same as Page1. You can define the SQL statement as a global variable and re-use it in your second query. just make sure to use closeCursor(); to close your db connection.
On submit/refresh the same predefined data in my array is added. How do i stop it being added more than once. I'd like to get rid of the data in my array if possible and just catch user input from the form which then is submitted to the array but i'm not sure how. Also how can i get my form to submit to my SQLite database, i think i need to add an INSERT INTO statement somewhere. Any help would be nice as i need this finished soon. :(
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Input</title>
<link href="css/style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<?php
try {
$dbh = new PDO('sqlite:mydb.sqlite3');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->exec("CREATE TABLE IF NOT EXISTS test (
name VARCHAR(30),
gender VARCHAR(30),
age INTEGER)"
);
$data = array( //Want to remove this prewritten data and store user input instead.
array('name' => 'Daniel', 'gender' => 'Male', 'age' => '21')
);
$insert = "INSERT INTO test (name, gender, age)
VALUES (:name, :gender, :age)";
$stmt = $dbh->prepare($insert);
foreach ($data as $m) {
$name = $m['name'];
$gender = $m['gender'];
$age = $m['age'];
$stmt->bindParam('name', $name);
$stmt->bindParam('gender', $gender);
$stmt->bindParam('age', $age);
$stmt->execute();
}
$result = $dbh->query('SELECT * FROM test');
$dbh = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
<div id="wrapper">
<div class="banner1">
<h2>Input</h2>
</div>
<form id="form" method="post">
Name:<br>
<input type="text" name="name[0]"/> <br>
Gender:<br>
<input type="text" name="gender[0]"/> <br>
Age:<br>
<input type="number" name="age[0]" min="1" max="99"/> <br>
<input id="submit" type="submit" value="Input">
</form>
</div>
<div id="results">
<div class="banner2">
<h2>Results</h2>
</div>
<div class="data">
<?php
unset($_POST['submit']);
$data=$_POST;
foreach ($result as $row) {
echo $row['name'] . " ";
echo $row['gender'] . " " ;
echo $row['age'] . "<br>" . " ";
}
?>
</div>
</div>
</body>
</html>
Here is a screenshot so you can grasp an idea of the form and how i'd like it to work. The results section is just generated from the array so i can see what is being inputted, but i'd like the input form to send data to the SQLite database that i have created/connected to above. Thank you.
First you have to test if Post exists
And second, check if the user already exist
if (isset($_POST)) {
// check for existing user
// Save
}
I would very much like to know how to add a random salt to the following code, I've been looking around the Internet, but I haven't figured it out yet, at least not the "PDO way" (if it even makes a difference)?
Anyway, I've got this code:
login.php:
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/style.css" />
</head>
<body>
<div id="loginForm">
<?php
// form is submitted, check if acess will be granted
if($_POST){
try{
// load database connection and password hasher library
require 'libs/DbConnect.php';
require 'libs/PasswordHash.php';
// prepare query
$query = "select email, password from users where email = ? limit 0,1";
$stmt = $con->prepare( $query );
// this will represent the first question mark
$stmt->bindParam(1, $_POST['email']);
// execute our query
$stmt->execute();
// count the rows returned
$num = $stmt->rowCount();
if($num==1){
//store retrieved row to a 'row' variable
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// hashed password saved in the database
$storedPassword = $row['password'];
// salt and entered password by the user
$salt = "whatever";
$postedPassword = $_POST['password'];
$saltedPostedPassword = $salt . $postedPassword;
// instantiate PasswordHash to check if it is a valid password
$hasher = new PasswordHash(8,false);
$check = $hasher->CheckPassword($saltedPostedPassword, $storedPassword);
/*
* access granted, for the next steps,
* you may use my php login script with php sessions tutorial :)
*/
if($check){
echo "<div>Access granted.</div>";
}
// $check variable is false, access denied.
else{
echo "<div>Access denied. <a href='login.php'>Back.</a></div>";
}
}
// no rows returned, access denied
else{
echo "<div>Access denied. <a href='login.php'>Back.</a></div>";
}
}
//to handle error
catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
}
// show the registration form
else{
?>
<!--
-where the user will enter his email and password
-required during login
-we are using HTML5 'email' type, 'required' keyword for a some validation, and a 'placeholder' for better UI
-->
<form action="login.php" method="post">
<div id="formHeader">Website Login</div>
<div id="formBody">
<div class="formField">
<input type="email" name="email" required placeholder="Email" />
</div>
<div class="formField">
<input type="password" name="password" required placeholder="Password" />
</div>
<div>
<input type="submit" value="Login" class="customButton" />
</div>
</div>
<div id='userNotes'>
New here? <a href='register.php'>Register for free</a>
</div>
</form>
<?php
}
?>
</div>
</body>
</html>
register.php
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/style.css" />
</head>
<body>
<div id="loginForm">
<?php
// save the username and password
if($_POST){
try{
// load database connection and password hasher library
require 'libs/DbConnect.php';
require 'libs/PasswordHash.php';
/*
* -prepare password to be saved
* -concatinate the salt and entered password
*/
$salt="whatever";
$password = $salt . $_POST['password'];
/*
* '8' - base-2 logarithm of the iteration count used for password stretching
* 'false' - do we require the hashes to be portable to older systems (less secure)?
*/
$hasher = new PasswordHash(8,false);
$password = $hasher->HashPassword($password);
// insert command
$query = "INSERT INTO users SET email = ?, password = ?";
$stmt = $con->prepare($query);
$stmt->bindParam(1, $_POST['email']);
$stmt->bindParam(2, $password);
// execute the query
if($stmt->execute()){
echo "<div>Successful registration.</div>";
}else{
echo "<div>Unable to register. <a href='register.php'>Please try again.</a></div>";
}
}
//to handle error
catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
}
// show the registration form
else{
?>
<!--
-where the user will enter his email and password
-required during registration
-we are using HTML5 'email' type, 'required' keyword for a some validation, and a 'placeholder' for better UI
-->
<form action="register.php" method="post">
<div id="formHeader">Registration Form</div>
<div id="formBody">
<div class="formField">
<input type="email" name="email" required placeholder="Email" />
</div>
<div class="formField">
<input type="password" name="password" required placeholder="Password" />
</div>
<div>
<input type="submit" value="Register" class="customButton" />
</div>
<div id='userNotes'>
Already have an account? <a href='login.php'>Login</a>
</div>
</div>
</form>
<?php
}
?>
</div>
</body>
</html>
Now, how do I create a randomly generated salt?
Use password_hash (as of PHP 5.5). It will take care of everything for you.
There is a compatibility wrapper for older PHP versions.