MYSQL AES_ENCRYPT issues - php

I have a simple application that needs to store sensitive data in a Wordpress installation.
The data comes from the user via a Form, and up until now, I have been storing the data using $wpdb->insert, however as we get closer to launching this project, I want to make sure that sensitive user information is encrypted, and only decrypted when read.
I have no clue how to make this work using the $wpdb class, so I resorted to using mysqli for this component. So far, I run the $wpdb->insert statement to insert all the normal data, then open a new connection to try and insert the sensitive data.
$id = $wpdb->insert_id;
$servername = 'localhost';
$username = 'root';
$password = 'root';
$db = 'wp_database';
$conn = new mysqli( $servername, $username, $password, $db );
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch Data and store it
$sud = $form['sens_user_data'];
$key = 'mysecretkey';
$tbl = $wpdb->prefix . 'sensitive';
$sql = "UPDATE $tbl SET sens_user_data = AES_ENCRYPT(?, ?) WHERE id = ?";
if ( $stmt = $conn->prepare($sql) ) {
$stmt->bind_param('ssi', $sud, $key, $id);
$stmt->execute();
} else {
$error = $conn->errno . ' ' . $conn->error;
ChromePhp::log($error);
}
$conn->close();
This appears to work correctly, except all the values always encode to a single character, and then decode to NULL
What am I doing wrong?

Related

Select and print out Data from MySQL with php, not working

I have a table ("module databas") in a database in MySQL and I need to print out that table (very simple, two rows "Fnamn" and "Enamn" with names in it) on the server by writing a php script and using MySQL. Problem is : it doesn't work. The html part of the document (.php) works perfectly fine (the h1 appears on the screen) but I get nothing else. What could be the problem ?
Tried a few different ways to do it, even by copy/pasting from w3 schools (https://www.w3schools.com/php/php_mysql_select.asp) and changing a few variables, but nothing (had a "0 results" with this W3 one, and now nothing with the new one).
<h1>Script modul</h1>
<?php
$servername = "localhost";
$username = "antony";
$password = "thepassword";
$dbname = "antony";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT * FROM moduledatabas";
$result = mysqli_query($query);
if (!$result) {
$message = 'Invalid query: ' . mysqli_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while ($row = mysqli_fetch_assoc($result)) {
echo $row['Fnamn'];
echo $row['Enamn'];
}
mysqli_free_result($result);
You have not pass $conn in your mysqli_query(),just change your code like below :
$query = "SELECT * FROM moduledatabas";
$result = mysqli_query($conn,$query);
For more info refer mysqli_query

Inserting fields to MySQL Database through PHP not working

I am trying to insert values from gravity form submissions into mysql database using php, but nothing is showing up in my database when I try it:
Here is my code:
add_action("gform_after_submission_17", "push_fields", 10, 2);
function push_fields($entry, $form){
$title = $entry[1];
$location = $entry[1];
global $connection;
$query = ("INSERT INTO events(title, location) VALUES ($title, $location)");
$result = $connection->query($query);
}
I have already connected to the database, as I have used other functions that are pulling data already in the database:
$servername = '127.0.0.1';
$username = '*******';
$password = '*******';
$dbname = '*******';
$connection = new mysqli($servername, $username, $password, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
Please let me know if there is any other info you need.
EDITED (TO TEST FOR ERRORS):
add_action("gform_after_submission_17", "input_fields", 10, 2);
function add_entry($entry){
$title = mysql_real_escape_string($entry[1]);
$location = mysql_real_escape_string($entry[2]);
global $connection;
$query = ("INSERT INTO events(title, location) VALUES ('$title' , '$location')");
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
if($result){
echo 'Query OK';
}else{
echo 'Query failed';
}
}
This may be unhelpful if you're deliberately connecting to the DB; however, you might consider using the GFAPI.
https://docs.gravityforms.com/api-functions/#add-entry

Convert plain text password in mysql database to bcrypt encrypted password

I have mysql database with around 500 records. There is a column password which is currently containing plain text passwords.
I want to covert these passwords to encrypted with bcrypt. How can I do it from phpmyadmin ?
Second appended question : what will be login page coding to check this encrypted password and let member get in ? ( I am using mysqli)
First of all, backup your db... Then you have to do something like this...
Not knowing your app I can just make an example, this probably won't work in your current production code.
$servername = "YOUR_SERVER";
$username = "YOUR_USERNAME";
$password = "YOUR_PASSWORD";
$dbname = "YOUR_DB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, password FROM your_table";
$result = $conn->query($sql);
$newPasswords = [];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$newPasswords[] = ["id" => $row["id"], "newPass" = "YOUR_PASSWORD_ENCRYPTED_WITH_BCRYPY"];
}
} else {
echo "0 results";
}
foreach($newPasswords as $user) {
$sql = "UPDATE your_table SET password = $user["newPass"] WHERE id = $user["id"]";
$result = $conn->query($sql);
}
$conn->close();
After this, you can change your app to login the user taking care of the new encrypted password. To encrypt with bcrypt in PHP look here.
Again remember to backup your database before any operation!

Query MySQL with PHP

I am trying to query a MySQL database with PHP and return the results as JSON. I'm new to PHP and web development so I'm not sure what I'm doing wrong. I've set up the database using MAMP. My parameters are being printed but I'm not getting the JSON. I've gotten this far with the help of a tutorial.
EDIT: I just went into phpMyAdmin to make sure it was working and when I click on Server:localhost:8889, a window pops up that says Error in processing request. Error code 404.
I'm thinking this is the problem, I'm just not sure why it isn't working. I may reinstall MAMP.
<?php
$user = 'root';
$password = 'root';
$db = 'TestDB';
$host = '127.0.0.1';
$port = '8889';
$first_name = filter_input(INPUT_GET, 'first_name');
$last_name = filter_input(INPUT_GET, 'last_name');
$membership_number = filter_input(INPUT_GET, 'membership_number');
echo $first_name;
echo $last_name;
echo $membership_number;
// Create connection
// $con = mysqli_connect("localhost", "root", "root", "TestDB");
// $con = mysqli_connect("localhost", "root", "root", "TestDB", "8889", $socket);
$link = mysqli_init();
$con = mysqli_real_connect($link, $host, $user, $password, $db, $port);
// Check connection
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = \'$first_name\' and LAST_NAME = \'$last_name\' and MEMBERSHIP_NUMBER = \'$membership_number\'";
$result = mysqli_query($con, $sql);
if(!$result) {
die('Query failed: ' . mysqli_error());
}
// Check for results
// if ($result = mysqli_query($con, $sql)) {
if($result) {
// If there are results, create results array and a temporary one to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
// while($row = $result->fetch_object()) {
while($row = mysqli_fetch_object($result)) {
// Add each row to the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo $tempArray;
echo $resultArray;
echo $result;
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
You need to change you $sql variable to remove the escapes on the single quotes. They register as part of the string because you are using double-quotes to wrap it. Basically, you're telling the database to run the query "SELECT * FROM NAME WHERE FIRST_NAME = \'John\' and LAST_NAME = \'Smith\' and MEMBERSHIP_NUMBER = \'VRX78435\'". This will error if you run it directly because the escape characters are not escaping.
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = '$first_name' and LAST_NAME = '$last_name' and MEMBERSHIP_NUMBER = '$membership_number'";
That should fix it for you.
There may also be an issue with your connection to the server. mysqli_query() uses the results of mysqli_connect() to run the query. mysqli_real_connect() only returns a boolean value, so it is invalid for this particular use (at least it failed to work on my server).
This would be a simple matter of replacing the $con and then you can drop the $link variable.
$con = mysqli_connect($host, $user, $password, $db, $port);
These changes, and assuming the $first_name, $last_name, and $membership_number are all valid, allowed your script to run for me, so I hope this helps.
Seems you are using procedural style coding
Instead of
while($row = $result->fetch_object()) {
You need mysqli_fetch_object in procedural style
while($row = mysqli_fetch_object($result)) {

query error when access clearDB database using php on Heroku

I can access clearDB database well by using Mysql Workbench.
But when I query database by using php on Heroku, it always fail.
This is my code:
$url=parse_url(getenv("CLEARDB_DATABASE_URL"));
$dbhost = $url["host"];
$dbuser = $url["user"];
$dbpass = $url["pass"];
$dbname = substr($url["path"],1);
mysqli_connect($dbhost, $dbuser, $dbpass);
mysqli_select_db($dbname);
$sql = "SELECT * FROM `user_info` WHERE `user_account`='".$user_account."'";
$result = mysqli_query($sql) or die('MySQL query error');
user_account is a table in the database, $user_account is a input variable from client user
help me
thanks
You're not passing the link to mysqli_query(). You need to either do that, or use the object oriented style and call query() on the connection.
You also have a possible SQL injection there, because $user_account could contain "foo' OR 1 OR '", returning all rows (and that's just a simple, not very evil case), so you should escape that using mysqli_real_escape_string(), or even better, use prepared statements.
Finally, instead of or die(), how about extracting error information properly, or even configuring mysqli to throw exceptions?
<?php
$url = parse_url(getenv("CLEARDB_DATABASE_URL"));
$server = $url["host"];
$username = $url["user"];
$password = $url["pass"];
$db = substr($url["path"], 1);
$conn = new mysqli($server, $username, $password, $db);
$sql = "SELECT * FROM `user_info` WHERE `user_account`='".$conn->real_escape_string($user_account)."'";
if($result = $conn->query($sql)) {
foreach($result as $row) {
// ...
}
} else {
throw new Exception($conn->error);
}

Categories