Mysqli AES_DECRYPT - mysqli

I wonder if any of you can help me with this. I have no trouble encrypting a field and writing it to a database. For example:
$query= mysqli_query($mysqli,"INSERT INTO users (surname) VALUES (AES_ENCRYPT('Blenkinsop','mypassword'))");
The problem comes when trying to get it out again:
$query = mysqli_query($mysqli,"SELECT AES_DECRYPT(surname,'mypassword') FROM users WHERE userID = 1");
while($row = $query->fetch_assoc()){
[$row['surname']]; }
echo $row[0];
I have tried a number of variants, including echo $row['surname']
The error give is: "Undefined index: surname in line...", and the line refers to the line: [$row['surname']].
However, at the bottom of the error screen it says:
$row = array (size=1)
'AES_DECRYPT(surname,'mypassword')' => string 'Blenkinsop' (length=10)
Se the decryption is working; I just cannot find the right syntax to get it out.
If I just run the query without decryption it runs fine with no errors, and echos the still encrypted name:
$query = mysqli_query($mysqli,"SELECT surname FROM users WHERE userID = 1");
Any help would be much appreciated.
Many thanks
Steve Moss

column type surname = varbinary (50)
$query = mysqli_query($mysqli, "SELECT *, CAST(AES_DECRYPT(surname,'mypassword') AS CHAR(50)) surname FROM users WHERE userID = 1");

Related

Magento2: wrong config data value per store

I am trying to get some Magento2 custom core_config_data values, as explained in other topics, but I have some wrong values related to the store IDs. I will try to explain, let's start with some relevant code:
public function __construct(
\Psr\Log\LoggerInterface $logger,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig) {..}
{
$store = $this->storeManager->getStore();
$this->logger->debug($store->getId() . ": " . $store->getCode());
$message = $this->scopeConfig->getValue(self::CONF_MESSAGE,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE);
$link = $this->scopeConfig->getValue(self::CONF_LINK,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE);
What happens here is that the store ID and the store code are correct.
In the logs I see
main.DEBUG: 3: tedesco
The values I got in $message and $link are not correct: they are the values of another store (the correct store ID should be 3 as shown from the debug log, but the value is the one from the store with ID 1).
Of course I have checked the DB and the values are just fine as shown in the picture: .
Magento 2.1.4.
Any hints?
Thanks in advance.
What happens if you pass store or store id to 3rd param?
$message = $this->scopeConfig->getValue(self::CONF_MESSAGE,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store);

Powershell Multiple variables in foreach loop getting AWS-EC2 instance info

I need to get instanceId and PrivateIpAddress from all my EC2 instances in my environment and insert into table. I have this but doesn't seem to work. I seem to get everything not just the IP and ID.
$instancestate = (get-ec2instance).RunningInstance
foreach ($instances in $instancestate)
{
$query = "INSERT INTO prodinstances (Idinstance, IPAddress)
VALUES ('$instances.InstanceId','$instances.PrivateIpAddress')"
$Rows = Execute-MySQLNonQuery $conn $query
}
If I change the code
$instancestate = (get-ec2instance).RunningInstance.InstanceId
I get the ID and can insert it in the database. I can also change it to
$instancestate = (get-ec2instance).RunningInstance.PrivateIpAddress
and get the IPAddress and insert that into the database, but when i combine them I get all the info for the EC2 instances which does have .instanceId and .PrivateIpAddress in the list when I hover over the variable $instances. Any Idea how to get both those parameters. My code seems correct but alas it is not...
"VALUES ('$instances.InstanceId'"
is the same as
"VALUES ('" + $instances + ".InstanceId'"
Now it doesn't seem correct. You need $() around it, inside the string:
"VALUES ('$($instances.InstanceId)'"
Fixed works like a charm...
$instancestate = (get-ec2instance).RunningInstance
foreach ($instances in $instancestate)
{
$query = "insert into prodinstances (idinstance,IPAddress) VALUES ('$($instances.InstanceId)', '$($instances.PrivateIpAddress)')
ON duplicate key update idinstance='$($instances.InstanceId)',IPAddress='$($instances.PrivateIpAddr ess)'"
$Rows = Execute-MySQLNonQuery $conn $query
}

mysqli bind_param not updating table in database

I'm trying to update a table from a database with this code, but it keeps returning a fatal error
$stmt = $mysqli->prepare("UPDATE $tbl_name SET cart = ? WHERE username = $myUsername");
$stmt->bind_param('s', $chosenParts2);
$stmt->execute();
$stmt->close();
Your SQL Statement is wrong. So evtl. Table or field isn't existing. So just debug
UPDATE $tbl_name SET cart = ? WHERE username = $myUsername
Just add the following could after $mysqli->prepare
echo $mysqli->error;
and it should be clear why you got this error. The error unknown column is because $myUsername is not escaped, you just bind this variable too.
$stmt = $mysqli->prepare("UPDATE $tbl_name SET cart = ? WHERE username = ?");
$stmt->bind_param('ss', $chosenParts2, $myUsername);
$stmt->execute();
$stmt->close();

Where is my num_rows failing?

<?php
$link = mysqli_connect('localhost','root','root');
$link->query('CREATE DATABASE IF NOT EXISTS users');
$link->Select_db('users');
$sql='SELECT id FROM users WHERE email = '.$useremail.' AND username = '.$username;
$results = $link->query($sql);
$numrows = $results->num_rows;
if ($numrows == 1) {
#update user information
} else {
#failed to update
}
?>
It only works part of the time, and i'm not able to nail down an error from it one way or the other. I can confirm that the error pops up on the $numrows=$results->num_rows; line, but as for why, i'm lost. Occasionally it will work as intended, so any and all advice on what i can do to fix it, or at least helping me understand it better is greatly appreciated. Thanks!
Use Double Quotation for query and varchar/string pass with single quotation
$sql="SELECT id FROM users WHERE email = '".$useremail."' AND username = '".$username."'";
$results = $link->query($sql);
$numrows = $results->num_rows();
The reason that your call to num_rows generated an error is that your query had an error, and query() returned false instead of a valid result resource. Because it's a fatal error to try to call a method on a false value, you should always check the return value of query() before using it. Example:
if (!($result = $link->query($sql))) {
die($link->error);
}
Problems with your query:
You create a database named users and make that the default database, then you run a SELECT query from a table named users. There would be no tables in a database you have just created. In SQL, we use SELECT against tables, not databases (these are two different things, analogous to files contained in a directory on a filesystem).
You don't quote the string arguments in your SQL statement. For example, this SQL would be an error:
SELECT id FROM users WHERE email = bill#example.com AND username = bill
It should be this instead:
SELECT id FROM users WHERE email = 'bill#example.com' AND username = 'bill'
I know the quotes get confusing, because you have PHP string quotes and then SQL string quotes, but here are several ways of accomplishing it:
$sql='SELECT id FROM users WHERE email = \''.$useremail.'\' AND username = \''.$username.'\'';
$sql="SELECT id FROM users WHERE email = '".$useremail."' AND username = '".$username."'";
$sql="SELECT id FROM users WHERE email = '{$useremail}' AND username = '{$username}'";
I'm not sure if you have protected your PHP variables appropriately. You must never interpolate PHP variables into SQL strings unless you have escaped the content of the variables.
$useremail_esc = $link->real_escape_string($useremail);
$username_esc = $link->real_escape_string($username);
$sql="SELECT id FROM users WHERE email = '{$useremail_esc}' AND username = '{$username_esc}'";
But it would be better to use prepared statements with parameter placeholders. This is easier to use than escaping variables, and it's more reliable. Here's an example:
$sql="SELECT id FROM users WHERE email = ? AND username = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("ss", $useremail, $username);
$stmt->execute();
$result = $stmt->get_result();
Notice that you don't use escaping when you use parameters, and you don't put SQL quotes around the ? placeholders.

iDB2Commands in Visual Studio 2010

These are the basic things I know about iDB2Commands to be used in Visual Studio 2010. Could you please help me how could I extract data from DB2? I know INSERT, DELETE and Record Count. But SELECT or Extract Data and UPDATE I don't know.
Imports IBM.Data.DB2
Imports IBM.Data.DB2.iSeries
Public conn As New iDB2Connection
Public str As String = "Datasource=10.0.1.11;UserID=edith;password=edith;DefaultCollection=impexplib"
Dim cmdUpdate As New iDB2Command
Dim sqlUpdate As String
conn = New iDB2Connection(str)
conn.Open()
'*****Delete Records and working fine
sqlUpdate = "DELETE FROM expusers WHERE username<>#username"
cmdUpdate.Parameters.Add("username", iDB2DbType.iDB2Date)
cmdUpdate.Parameters("username").Value = ""
'*****Insert Records and working fine
sqlUpdate = "INSERT INTO expusers (username, password, fullname) VALUES (#username, #password, #fullname)"
cmdUpdate.Parameters.Add("username", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters.Add("password", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters.Add("fullname", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters("username").Value = txtUsername.Text
cmdUpdate.Parameters("password").Value = txtPassword.Text
cmdUpdate.Parameters("fullname").Value = "Editha D. Gacusana"
'*****Count Total Records and working fine
Dim sqlCount As String
Dim cmd As New iDB2Command
sqlCount = "SELECT COUNT(*) AS count FROM import"
cmd = New iDB2Command(Sql, conn)
Dim count As Integer
count = Convert.ToInt32(cmd.ExecuteScalar)
'*****Update Records and IT IS NOT WORKING AT ALL
sqlUpdate = "UPDATE expusers SET password = #password WHERE RECNO = #recno"
cmdUpdate.Parameters.Add("recno", iDB2DbType.iDB2Integer)
cmdUpdate.Parameters.Add("password", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters("recno").Value = 61
cmdUpdate.Parameters("password").Value = txtPassword.Text
cmdUpdate.Connection = conn
cmdUpdate.CommandText = sqlUpdate
cmdUpdate.ExecuteNonQuery()
conn.Close()
Please help me how to code the SELECT query wherein I could extract/fetch data from DB2 Database. Also, how could i update the records in the database.
Thanks!
Instead of ExecuteNonQuery(), look at ExecuteReader(). I don't have VS2010 installed, but try something like this:
iDB2Command cmdSelect = new iDB2Command("SELECT username, password, fullname FROM expusers", conn);
cmdSelect.CommandTimeout = 0;
iDB2DataAdapter da = new iDB2DataAdapter(cmdSelect);
DataSet ds = new DataSet();
da.Fill(ds, "item_master");
GridView1.DataSource = ds.Tables["expusers"];
GridView1.DataBind();
Session["TaskTable"] = ds.Tables["expusers"];
da.Dispose();
cmdSelect.Dispose();
cn.Close();
See: http://gugiaji.wordpress.com/2011/12/29/connect-asp-net-to-db2-udb-for-iseries/
If you aren't trying to bind to a grid, look at iDB2Command.ExecuteReader() and iDB2DataReader()
The DELETE is working fine? The code has the parameter type for "username" set to iDB2Date. The INSERT has "username" set to iDB2VarChar. How is the column defined in the table? Char, Varchar or Date?
On the UPDATE, you reference RECNO, but that does not seem to be a column in the table. Updating a relational database table by row number is a bad idea - the row numbers are not guaranteed to stay constant. If you are just testing, as I think you are, don't use RECNO, use RRN(). The DB2 for i syntax is WHERE rrn(expusers) = #recno
To help your testing, do a SELECT without a WHERE clause and list out all the rows. Make sure the name stored in the username column matches the name you are trying to update. Pay particular attention to the case of the data. If the name in expusers looks like "EDITHA D. GACUSANA", and #username is "Editha D. Gacusana" then it will not match on the WHERE clause.