How do I use AES_Decrypt - php

I know this question has been asked a billion times as I've spent the last 2 weeks looking at all the previously asked questions and answers
but none of them actually have an understandable answer. So my question is this, I have a form that I'm passing the data input by users into a mysql
database and a portion of that data is encrypted with AES_Encrypt. When I check the database I can see the data has been encrypted so I'm good on the encryption part.
My issue lies in the decryption part. I've tried multiple variations from previous questions asked with no success, This is what I have so far,
//ENCRYPTING DATA
require 'path to key.php';
$sql = "INSERT INTO applications "(fname, lname, dob, ssn) VALUES ('$fname', '$lname', '$dob', AES_ENCRYPT('$ssn', '".$aeskey."')";
The code above works fine to encrypt the string.
This is where I'm confused, I'm wanting to select all the data associated with the ID for a record and decrypt the encrypted data for that record as well,
for example I have a search form that pulls up all the records in the database, you can then select to view a record and the results display in a form similar to the form used
to input the information.
So in my form to view records I have the following code.
//DECRYPT DATA
require 'path to key.php';
$conn = new mysqli($servername, $username, $password, $dbname);
$data = "SELECT * FROM $tbl_name where ID = $id";
$query = mysqli_query($conn, $data);
$data2 = mysqli_fetch_array($query);
<input type = "text" name="fname" value="<?php echo $data2['fname']?>"/>
<input type = "text" name="lname" value="<?php echo $data2['lname']?>"/>
<input type = "text" name="dob" value="<?php echo $data2['dob']?>"/>
<input type = "text" name="ssn" value="<?php echo $data2['ssn']?>"/><-----This will display the encrypted data in the encrypted form
So do I need to decrypt the encrypted data from the input box like
<input type = "text" name="ssn" value=<?php echo [AES_DECRYPT('ssn', '$aeskey')]?>"/> <---Doesn't work
or do I need to do something like this:
$sql SELECT * FROM $tbl_name (AES_DECRYPT('ssn', '$aeskey')) WHERE ID=$id;
Or am I totally wrong in how I think AES_DECRYPT should be used?

In the INSERT you use AES_ENCRYPT (of MySQL); then you have in your SELECT apply AES_DECRYPT; ejem:
SELECT fname, lname, dob, AES_DECRYPT(ssn, yourAESKey) as ssn
FROM applications [wHERE ... and other more that you require]
See that AES_DECRYPT have alias to return of result.
EDITED
Only change in $data the string with the SQL:
$data= "SELECT fname, lname, dob, AES_DECRYPT(ssn, yourAESKey) as ssn
FROM applications [WHERE ... and other more that you require]"
You line: <input type = "text" name="ssn" value="<?php echo $data2['ssn']?>"/><-----This will display the encrypted data in the encrypted form not change; unless instead of ssn (all in lowercase) in the alias you change some letter or all the letters to capital letters, you assign another alias name to the decrypted text; In order not to be ssn (in lower case).

Related

Find and Post in table using php

I'm trying to upload data to a existing User database I have stored online. I need to post the user phone number string in the user specified row. Using android and php, is there any way to post extra info in an existing row?
I think I'm not choosing WHERE to put that extra info.
<?php
require "indioPhP.php";
$username = $_POST["username"];
$phoneNumber = $_POST["phoneNumber"];
$statement = mysqli_prepare($con, "SELECT * FROM User WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
$sql ="insert into User values('$phoneNumber')";
if(mysqli_query($con,$sql)){
echo "Gracias por registrarte!";
} else{
echo "error in insertion".mysqli_error($con);
}
?>
Ok now i see your Problem:
Update User set phonenumber=? where username=?
You Need something like this ? it's only one query where you search the user and Change it. Try to read more about SQL. Your code Looks a bit confused, with prepared Statements and normal statments in the same block.
Edit:
The statement insert adds a new line in the table wheras update modifies an existing one. Assuming your table User has 4 columns: username, firstname, lastname, phonenumber, for insert, the syntax is either
insert into user values("jdoe", "John", "Doe", "555 7565")
or
insert into user(username, phonenumber) values ("jdoe", "555 7565")
In the first case, as columns are not specified, you must give all of them.
In the second case, you insert a new line specifying only some columns. The other ones will take their default values. If a missing column doesn't have a default value, you will have an error.

mysql auto increment and unique field

I am writing the following command in php:
$query="insert into tableone (user_name, password, name, email) values('$user_name', '$password', '$name', '$email')";
if(mysql_query($query))
{
header("Location:thislocation.php");
} else {
echo '<br><br><font color="red"><strong>Username or EmailId already exists. Please try different Username.<br> If you have forgotten your Password <u><i>click here</i></u>.</strong></font><br>';
}
Here in mysql-db I have made name and email field as unique and id as auto increment, so that no two people have same registration records. The problem is that, if someone uses same username or email, the query fails and else statement is executed. But, it auto-increments the id, without getting records added in db. If someone after that registers successfully, he gets an id not 2 more than the previous one.
How to get auto-incremented just once?
There's no real fix; this is how auto-increment IDs work. IDs are not designed to be "clean", they're designed to fullfill a need to be able to link data together.
It'll be a huge amount of work for your database to keep them in order and (here's the most important part) nobody cares about whether they're aligned anyway. They're numbers without a real-world meaning (by definition of being a database ID) so nothing about them should matter.
The only reason they're "in order" normally is because it's an easy way to generate them.
What you need to do is run an num_rows on it, before you insert it. what num_rows do, it count how many records the SELECT returns, so if it returns 1, there is a place in the database where there are a match, if it returns 0, there are no match
$selectSql = "SELECT * FROM tableone WHERE name= '".$name."' OR email = '".$email."'";
$result = mysql_query($selectSql, $YOUR_DATABASECONNECTION);
$num_rows = mysql_num_rows($result);
if($num_rows){
echo "email or name is already taken";
}else{
$query="insert into tableone (user_name, password, name, email) values('$user_name', '$password', '$name', '$email')";
if(mysql_query($query))
{
header("Location:thislocation.php");
} else {
echo '<br><br><font color="red"><strong>Username or EmailId already exists. Please try different Username.<br> If you have forgotten your Password <u><i>click here</i></u>.</strong></font><br>';
}
}
This is a good way to secure, that the error you're talking about wont happend

Storing different values in one same field database php

I have this two tables,
exam table
ID, title, creator
exam_settings table
id //(simply for managing rows and edits/updates)
"1", "2", "3" // etc
quiz_id
"55912" // or so on
type
"question", "answer"
ref_number
"1", "2" // This is basically Question 1, Question 2, Answer 1 etc.
value
"What is ...?" or "21" // The question or the answer
Now I have a problem storing the question and answer in the table, I used this html array question
<input type="text" name="quiztxtBox[]" > and <input type="text" name="answer[]" >
to get the inputs. But I wonder how to perform sql using this 2 arrays and store them in same field. Here is how my sql looks like.
$quiztxtBox = $_POST["quiztxtBox"]; //array
$answer = $_POST["answer"]; //array
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("elearning") or die(mysql_error()) ;
mysql_query("INSERT INTO exam_list (exam_name, creator) VALUES ('$files', 'admin')");
$lastid = mysql_query("SELECT ID FROM exam_list ORDER BY ID DESC LIMIT 0 , 1");
$id = implode($lastid);
mysql_query("INSERT INTO exam_setting (exam_id, type, ref_number, value) VALUES ('$id', 'othervalues')");
So I stored first the exam name and creator the after the exam questions and answer, thats the part where I am lost. Any Idea on this?
You can read the values of input text as array by this way.
<form name="" action="array.php" method="post">
<input type="text" name="quiztxtBox[]" >
<input type="text" name="answer[]" >
</form>
In array.php file
//get the array
$quiztxtBox=$_POST['quiztxtBox'];
$answer=$_POST['answer'];
//loop through the array
foreach($quiztxtBox as $key=>$quiztxtBox){
echo 'Question'.$quiztxtBox.'Answer'.$answer[$key];
//for storing in the same field.
//perform your sql query with this
$finalstring=$quiztxtBox.','.$answer[$key];
}

How to insert form data into table as foreign key?

I am working on an employee database which will store useraccount information. I have created the forms and am now working on getting the data from the forms into the database. My Users table has fields for first name, last name, email, etc. as well as foreign keys organization_id, supervisor_id, etc. So far I have the following code for inserting into the non-foreign-key fields:
$f_name = $_POST['firstName'];
$l_name = $_POST['lastName'];
$user_type = $_POST['userType'];
//etc...
$insert = "INSERT INTO Users(f_name, l_name, user_type, email, empl_status_id, reliab_status_id, secr_status_id, ";
$values = "VALUES($f_name, $l_name, $user_type, $email, $empl_status, $reliab_status, $secr_status, ";
if($w_username) {$insert .= "w_username, "; $values .= "'$w_username', ";});
$sql = $insert . $values;
All of those fields are required, except for w_username which may be left blank. Organization and Supervisor may also be left blank.
The problem is, when they are NOT null, I am not sure how to insert them into the database. In the form, the user may enter their organization in a text field which is linked to a datalist. The datalist should be populated by Organizations that have been previously entered. If a new Organization is entered, it should be added to the database, and consequently, the datalist.
So do I insert the OrganizationID if it's selected from the datalist? How do I do that? I thought maybe I would have to iterate through the list, but then if the list becomes very long eventually, wouldn't that be a problem?
Note: Please explain like I'm 5, I'm really new to this!
Try Something like below
<?php
//take OrganizationID as text from form (leave auto complete as it)
$sql = "select OrganizationID from org where Organization_name LIKE '".$_POST['OrganizationName']."'";
//execute it .....
if(mysql_num_rows()>0){
$id = $row['id']; //and put in foreign table
}
else{
// insert to org here and get last inserted id calling mysql_insert_id() ;
// and put in foreign table
}
?>

Error: Unknown column in 'where clause'

I have a form that is populated with mySQL db values upon loading the page. The data in the form can be edited and then a submit button that send the data to mysql to overwrite the values that were preloaded in the form. The fields are displayed in the form correctly but when changed and submitted I receive the following:
Error:Unkown column in 'where clause'.
I'm relatively new to working with mysql query's instead of taking the 'phpmyadmin' route ._.
Here's the query I used to fill the table with the original form data:
INSERT INTO mytable VALUES ("sunday", "name1", "price1"), ("monday", "name2", "$35"), ("tuesday", "name3", "$100"), ("wednesday", "name4", "$65"), ("thursday", "name5", "$5"), ("friday", "name6", "$57"), ("saturday", "name7", "$10");
Here's the sql query used to populate the form and then assigned to a variable by usingfetch_array
$sun_data = mysql_query("SELECT * FROM mytable WHERE day='sunday'")
or die(mysql_error());
... ...
$sun_info = mysql_fetch_array( $sun_data );
Then the form:
<form action="update_form.php">
<input type="text" name="sun_name" value="<?php echo $sun_info['name'] ?>" />
<input type="text" name="sun_price" value="<?php echo $sun_info['price'] ?>" />
Like I said the form updates fine but then when the form data is submitted to update_form.php I receive the error. Here is the form action update.php
$sun_day_change = $_POST['sun_name'];
$sun_price_change = $_POST['sun_price'];
$sunday = 'sunday';
$sql = "UPDATE mytable SET name = '$sun_day_change', price = '$sun_price_change' WHERE day = ".$sunday;
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
header('Location: http://localhost/form.php');
I'm assuming the issue is when I pass the values back to the database but since I have used almost the identical sql query to retrieve the values I'm not sure where I went wrong. Thanks for the help!
You are missing quotation marks in the update query, around $sunday.
$sql = "UPDATE mytable SET name = '$sun_day_change', price = '$sun_price_change' WHERE day = '".$sunday."'";

Categories