Issue With Mysqli Prepared Statement When Using AES_ENCRYPT - php

I am trying to do a simple insert into MySQL. I am using mysqli using prepared statements. Below is the code:
$sql_query = "UPDATE $table SET $name = AES_ENCRYPT(?,'$key') WHERE $id_name = '$_SESSION[$id_name]'";
$stmt = $mysqli->prepare($sql_query);
$stmt->bind_param('b', $value);
$stmt->execute();
Yes, I am declaring $mysqli with a connection to the mySQL database server earlier in the code. $key is also declared earlier in the script. Below is the output into the mySQL general log file when this code is invoked:
120104 10:46:18 359 Connect root#localhost on payday-loan-leads
359 Query SELECT table_location, id_name, encrypt FROM insert_information WHERE required_field_name = 'first_name'
359 Prepare UPDATE personal_info SET first_name = AES_ENCRYPT(?,'^&IK8uBo92X04jhAHPUH(Y(8p3)&^ndlkj32') WHERE personal_id = '5282'
359 Execute UPDATE personal_info SET first_name = AES_ENCRYPT('','^&IK8uBo92X04jhAHPUH(Y(8p3)&^ndlkj32') WHERE personal_id = '5282'
359 Close stmt
359 Quit
As you can see, mySQL is preparing the INSERT query but does not capture the value of $value. When I remove the AES_ENCRYPT from the $sql_query, it works like a charm:
$stmt = $mysqli->prepare("UPDATE $table SET $name = ? WHERE $id_name = '$_SESSION[$id_name]'");
$stmt->bind_param('s', $value);
So the problem is with the AES_ENCRYPT function of mySQL. I tried moving the function into the bind_param line and this did not work. Anyone have any ideas here?

You use b (blob) for binding in the aes version, but s (string) in the non-aes version. Try s in the AES version - it shouldn't matter WHERE a paramter appears in a query, as long as it's not use for a field or table name.

Related

update query not working in prepared statement with multiple where clause

I have the following update statement which does execute successfully but with no value change in the table.
$name = "John Doe"; //to update into John Stack
$chenna = "Mz"; $reg = 25; $km = 3;
$dbh = PDO Object
$stmt = $dbh->prepare("UPDATE `hl_customer` SET `name`=:hming, `address`=:chenna
WHERE `regd`=:regd AND `kum`=:km");
$stmt->bindParam(':hming', $name, PDO::PARAM_STR);
$stmt->bindParam(':chenna', $hmun, PDO::PARAM_STR);
$stmt->bindParam(':regd', $reg, PDO::PARAM_INT);
$stmt->bindParam(':km', $km, PDO::PARAM_INT);
$stmt->execute();
$affected = $stmt->rowCount();
Another tested code:
$stmt = $dbh->prepare("UPDATE `hl_customer` SET `name`=?, `address`=?
WHERE `regd`=? AND `kum`=?");
$stmt->execute([$name, $hmun, $reg, $km]);
$affected = $stmt->rowCount();
$stmt = $dbh->query("UPDATE `hl_customer` SET `name`='$name', `address`='$chenna'
WHERE `regd`='$reg' AND `kum`='$km'");
In order to update I kept changing the $name variable, yet there was no affected row. The row count always return 0. I did tested in both phpmyadmin(latest version) and mysql Workbench(latest) and the problem is still there. Then I tested again in mysql console, and it works as expected. But why is it not working in the code shown above, phpmyadmin and workbench. What could be the problem? Is my code wrong? I used mysql 8.0.12, php 5.6.* and php 7.1.*.
I did test it again without parameterized query, still it did not work. Now I begin to think that it is a kind of bug in php.
Thanks
Well i don't see anything wrong with your code try and verify if the number of columns in your table matches the number of paramaters you have because you said it works when you drop the last parameter

select sql row using pdo with where statement

This is my first time to try PDO and still learning it. I am more familiar in using mysql or mysqli in developing php system.
After deep searching and searching I still can't seem to understand how to query using PDO
In my code I used mysqli inside a function to be called in index.php
function getUsery(){
$ip = getIPAddress();
$query = mysqli_query("select userID from tblUsers where logged='1' AND ip='$ip'");
$row = mysqli_fetch_array($query);
$emp = $row['userID'];
$logged = $row['logged'];
$userlvl = $row['userLevel'];
$_SESSION['logged'] = $logged;
$_SESSION['userLevel'] = $userlvl;
return $emp;
}
I don't really know how to select sql query using PDO with 'where' statement. Most of what I found is using array with no 'where' statement
How can I select the userID where logged is equal to '1' and ip is equal to the computer's ip address and return and display the result to the index.php
There's SQL statement with WHERE in PDO
$sql = "SELECT * FROM Users
WHERE userID = ?";
$result = $pdo->prepare($sql);
$result->execute([$id]);
Assuming that you know how to connect database using PDO, here is how to select SQL with PDO.
$stmt = $db->prepare("select userID from tblUsers where logged = '1' AND ip = :ip");
$stmt->execute(array('ip' => $ip));
$listArray = $stmt->fetchAll();
Notice the :ip at the end of SELECT. If you don't use ? as a parameters, the prefix : is mandatory and the word after that should be the same as the key in the execute function.
EDIT
In case that the above code is inside the function and $db is outside the function, declare $db as global variable inside the function.
This one is imo one of best guides on PDO and how to use it:
https://phpdelusions.net/pdo
WHERE is a part of query and queries in PDO are not much different from pure *sql queries, just there is going on a bit filtering on execution. Read the guide carefully and you will be able to execute any query you need to.

Using PHP variable in SQL query

I'm having some trouble using a variable declared in PHP with an SQL query. I have used the resources at How to include a PHP variable inside a MySQL insert statement but have had no luck with them. I realize this is prone to SQL injection and if someone wants to show me how to protect against that, I will gladly implement that. (I think by using mysql_real_escape_string but that may be deprecated?)
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'hospital_name' AND value = '$q'";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried switching '$q' with $q and that doesn't work. If I substitute the hospital name directly into the query, the SQL query and PHP output code works so I know that's not the problem unless for some reason it uses different logic with a variable when connecting to the database and executing the query.
Thank you in advance.
Edit: I'll go ahead and post more of my actual code instead of just the problem areas since unfortunately none of the answers provided have worked. I am trying to print out a "Case ID" that is the primary key tied to a patient. I am using a REDCap clinical database and their table structure is a little different than normal relational databases. My code is as follows:
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'case_id' AND record in (SELECT distinct record FROM database.table WHERE field_name = 'hospital_name' AND value = '$q')";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried substituting $q with '$q' and '".$q."' and none of those print out the case_id that I need. I also tried using the mysqli_stmt_* functions but they printed nothing but blank as well. Our server uses PHP version 5.3.3 if that is helpful.
Thanks again.
Do it like so
<?php
$q = 'mercy_west';
$query = "SELECT col1,col2,col3,col4 FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
if($stmt = $db->query($query)){
$stmt->bind_param("s",$q); // s is for string, i for integer, number of these must match your ? marks in query. Then variable you're binding is the $q, Must match number of ? as well
$stmt->execute();
$stmt->bind_result($col1,$col2,$col3,$col4); // Can initialize these above with $col1 = "", but these bind what you're selecting. If you select 5 times, must have 5 variables, and they go in in order. select id,name, bind_result($id,name)
$stmt->store_result();
while($stmt->fetch()){ // fetch the results
echo $col1;
}
$stmt->close();
}
?>
Yes mysql_real_escape_string() is deprecated.
One solution, as hinted by answers like this one in that post you included a link to, is to use prepared statements. MySQLi and PDO both support binding parameters with prepared statements.
To continue using the mysqli_* functions, use:
mysqli_prepare() to get a prepared statement
mysqli_stmt_bind_param() to bind the parameter (e.g. for the WHERE condition value='$q')
mysqli_stmt_execute() to execute the statement
mysqli_stmt_bind_result() to send the output to a variable.
<?php
$q = 'Hospital_Name';
$query = "SELECT value FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
$statement = mysqli_prepare($conn, $query);
//Bind parameter for $q; substituted for first ? in $query
//first parameter: 's' -> string
mysqli_stmt_bind_param($statement, 's', $q);
//execute the statement
mysqli_stmt_execute($statement);
//bind an output variable
mysqli_stmt_bind_result($stmt, $value);
while ( mysqli_stmt_fetch($stmt)) {
echo $value; //print the value from each returned row
}
If you consider using PDO, look at bindparam(). You will need to determine the parameters for the PDO constructor but then can use it to get prepared statements with the prepare() method.

mysql query does not get updated due to apostrophe sign

$url = "example.com";
$data = json_decode($raw);
$pname=$data->name;
$sql="UPDATE `client` SET pname='$pname' WHERE url='$url'";
$query=mysql_query($sql,$link)or die(mysql_error());
When the json data is decoded, the value in variable $pname goes in client table. If there is an apostrophe sign (') in name then it throws an error. What changes can I make in the variable to send the name to database table?
example:
Jerry get updated with no issues
D'Cunha does not get updated as it has the apostrophe sign. The query becomes
"UPDATE `client` SET pname='D'Cunha' WHERE url='example.com'"
I found some articles but that does not say about how to find the apostrophe sign and change the variable value
use mysql_escape_string()
$sql="UPDATE `client` SET pname='".mysql_escape_string($pname)."' WHERE url='$url'";
and learn mysqli or PDO as mysql is deprciated and soon going to be drop
Use prepared statements. Mysqli or PDO. Here's an example with mysqli:
$url = "example.com";
$data = json_decode($raw);
$pname=$data->name;
$mysqli = new mysqli($host, $user, $password, $db);
$stmt = $mysqli->prepare("UPDATE client SET pname = ? WHERE url = ?");
$stmt->bind_param("ss", $pname, $url);
$stmt->execute();
Why shouldn't I use mysql_* functions in PHP?
Try this:
UPDATE client SET pname = 'D\'Cunha' WHERE url = 'example.com'

How do I write a prepared statement with an update?

I am using mysqli prepared statments and I am trying to write a prepared statement with an UPDATE, but I think I am off somewhere.
Here's my code:
$upload_folder = 'Some String';
$sql = 'UPDATE orders (upload_location)
SET (?)
WHERE order_id = 160';
$stmt = $conn->stmt_init();
if($stmt->prepare($sql)){
$stmt->bind_param('s', $upload_folder);
$location_inserted = $stmt->execute();
}
What am I doing wrong?
SET foo = ?
You haven't specified which column to update.
the correct sql-syntax for update is:
UPDATE table SET column = ?
you are using SET keqword instead of VALUES as it's supposed by query format.

Categories