It does not print the result. Dont know why. Everything is neatly commented
I get no error displays, no syntax blasphemes, it just does not print any result. However, I do know that the values are passed by the form to this processing php page, so the error is not in there. In the DB I have encrypted all fields except 'company'- Thus, I want to see if this will work by trying to fetch the results back.
// 1. Creating a new server connection
$db = new mysqli('localhost', 'root', '', 'developers');
if ($db->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
// 2, Creating statement object
$stmt = $db->stmt_init();
// 3, Creating a prepared statement
if($stmt->prepare("SELECT company FROM accesoweb WHERE username = AES_DECRYPT(?, 'salt')")) {
//4. Binding the variable to replace the ?
$stmt->bind_param('s', $username);
printf("Error: %d.\n", $stmt->errno);
// 5. Executing query
$stmt->execute();
// 6. Binding the result columns to variables
$stmt->bind_result($company);
// 7. Fetching the result of the query
while($stmt->fetch()) {
echo $company;
}
// 8. Closing the statement object
$stmt->close();
// 9. Closing the connection
$mysqli->close();
}
The inserting code that I just included in the MySQL was:
INSERT INTO accesoweb (company, username,email,password)
VALUES
('hola',
AES_ENCRYPT('maria','salt'),
AES_ENCRYPT('sumail','salt'),
AES_ENCRYPT('password',' salt')
);
So, that row above(actually, the "company" is what I am trying to recover through the PHP code
SELECT company FROM accesoweb WHERE username = AES_DECRYPT(?, 'salt')
Should be
SELECT company FROM accesoweb WHERE username = AES_ENCRYPT(?, 'salt')
OR
SELECT company FROM accesoweb WHERE AES_DECRYPT(username, 'salt') = ?
Related
This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I have a query with a parameter to bind stored in the session.
I tested the query on the database and it should return 1 row but it does not!
I tried everything. Its not an issue with the $id because I use it for another query and it is fully working:
$resultReturn = $con->prepare( 'SELECT `returns`.`return_id`, `returns`.`return_status` FROM
`agents` LEFT JOIN `returns` ON `returns`.`agent_id` = `agents`.`id` AND `agents`.`id` = ?');
$resultReturn->bind_param('i', $id);
$resultReturn->execute();
$resultReturn->fetch();
$resultReturn->store_result();
$resultReturn->bind_result($returnID, $returnStatus);
if($resultReturn)
{
echo $resultReturn->num_rows; //zero
while($row = $resultReturn->fetch_row())
{
echo $resultReturn->num_rows; //incrementing by one each time
}
echo $resultReturn->num_rows; // Finally the total count
}
$con -> close();
the first if returns always FALSE; If I set manually the id it works!
Here is my other query at the beginning of the same page (and its perfectly working):
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if (mysqli_connect_errno()) {
exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// We don't have the password or email info stored in sessions so instead we can get the results from the database.
$stmt = $con->prepare('SELECT password, email, role FROM agents WHERE id = ?');
// In this case we can use the account ID to get the account info.
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($password, $email, $role);
$stmt->fetch();
$stmt->close();
It is because I'm using the same connection for multiple queries?
Move fetch() after bind_result().
The correct order should be:
$resultReturn = $con->prepare(/* */);
$resultReturn->bind_param('i', $id);
$resultReturn->execute();
$resultReturn->store_result();
$resultReturn->bind_result($returnID, $returnStatus);
$resultReturn->fetch();
I am trying to build an override feature so users can manually remove a MySQL table row if they have the correct rights to do so. The user is prompted to input the same credentials used for program login as well as the uniqueID for the row that needs to be removed. Upon hitting the 'Submit' function, I run a series of if statements/ MySQL SELECT statements to check credentials, user rights and finally row Deletion with the result output as an alert.
However, my alert shows up blank and the row is not removed so I know there is a problem with my if statements. Upon testing, I believe the problem is when I try to use the previous query's results to run the next if statement logic.
How do I properly determine if the MySQL query returned a row using prepared statements?
All help is appreciated! Thank you!
My CODE:
if ((isset($_POST['overrideUsername'])) and (isset($_POST['overridePassword'])) and (isset($_POST['overrideUniqueID']))) {
$overridePasswordInput = $_POST['overridePassword'];
$overrideUsername = $_POST['overrideUsername'];
$overridePassword = ENCODE(($overridePasswordInput).(ENCRYPTION_SEED));
$roleID = '154';
$overrideUniqueID = $_POST['overrideUniqueID'];
//connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if(mysqli_connect_errno() ) {
printf('Could not connect: ' . mysqli_connect_error());
exit();
}
$conn->select_db($dbname);
if(! $conn->select_db($dbname) ) {
echo 'Could not select database. '.'<BR>';
}
$sql1 = "SELECT users.id FROM users WHERE (users.login = ?) AND (users.password = ?)";
$stmt1 = $conn->prepare($sql1);
$stmt1->bind_param('ss', $overrideUsername, $overridePassword);
$stmt1->execute();
$stmt1->bind_result($userID);
//$result1 = $stmt1->get_result();
if ($stmt1->fetch()) {
$sql2 = "SELECT * FROM rolestousers WHERE (rolestousers.userid = ?) AND (rolestousers.roleid = ?)";
$stmt2 = $conn->prepare($sql2);
$stmt2->bind_param('ss', $userID, $roleID);
$stmt2->execute();
$stmt2->store_result();
if ($stmt2->fetch()) {
$sql3 = "DELETE * FROM locator_time_track_out WHERE locator_time_track_out.uniqueid = ?";
$stmt3 = $conn->prepare($sql2);
$stmt3->bind_param('s', $overrideUniqueID);
$stmt3->execute();
$stmt3->store_result();
if ($stmt3->fetch()) {
echo 'Override Successful! Please scan the unit again to close it out.';
} else {
echo 'Could Not Delete Record from the table.';
}//End $sql3 if.
} else {
echo 'User does not have override permission. Please contact the IT Department.';
}//End $sql2 if.
} else {
echo 'Your login information is incorrect. Please try again. If the issue persists, contact the IT Department.';
}//End $sql1 if.
//Free the result variable.
$stmt1->free();
$stmt2->free();
$stmt3->free();
$stmt1->close();
//Close the Database connection.
$conn->close();
}//End If statement
NOTE: I am definitely sure my DB connection information is correct. The issue resides after I connect into the database. I have also tested the code using only the first if statement and get the blank alert so I'm not making it past the first if statement.
EDIT:: My php Script was definitely failing, but even earlier than expected, at the following code:
$overridePassword = ENCODE(($overridePasswordInput).(ENCRYPTION_SEED));
So my issue is that I need to properly compare the password and encryption seed information. However, the previous programmer used the following line to do the same process (which is obviously unsafe):
$querystatement = "SELECT id, firstname, lastname, email, phone, department, employeenumber, admin, usertype FROM users WHERE login=\"".mysql_real_escape_string($user)."\" AND password=ENCODE(\"".mysql_real_escape_string($pass)."\",\"".mysql_real_escape_string(ENCRYPTION_SEED)."\")";
$queryresult = $this->db->query($querystatement);
I will need to fix this issue before I can even test the functionality of the if logic using prepared statements.
Your are passing wrong variable for delete query
$stmt3 = $conn->prepare($sql3);
Please refer [ http://www.plus2net.com/php_tutorial/pdo-delete.php ]
I had some Prepared Statements working in PHP using mysqli. The requirements changed and now I'm supposed to move them to the DB, as Stored Procedures. This worked fine for most of the PSs, except for a couple that read the insertId for some further processing.
Ex:
$idAsdf = $stmtAsdf->insert_id;
where the PS performs an INSERT operation.
I've tried using an OUT parameter on the procedure which works fine on PHPMyAdmin, but can't connect it with the PHP server code outside the DB. I haven't found any example of this combination of elements being done. How can I get this insertId using both SPs and PSs?
Thanks
For PDO Prepared Statement you can use PDO::lastInsertId -http://php.net/manual/en/pdo.lastinsertid.php
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)");
try {
$dbh->beginTransaction();
$tmt->execute( array('user', 'user#example.com'));
print $dbh->lastInsertId();
$dbh->commit();
} catch(PDOExecption $e) {
$dbh->rollback();
print "Error!: " . $e->getMessage() . "</br>";
}
} catch( PDOExecption $e ) {
print "Error!: " . $e->getMessage() . "</br>";
}
?>
Just remember when using transaction return lastInsertId or store lastInsertId before commit.
For Stored Procedure - use LAST_INSERT_ID();
BEGIN
INSERT INTO test (name, email) VALUES ('value1', 'value2');
SET out_param = LAST_INSERT_ID();
END
EDIT 1 :
If you using MySQLi - then use mysqli_insert_id - http://php.net/manual/en/mysqli.insert-id.php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = mysqli->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
printf ("New Record has id %d.\n", $stmt->insert_id);
/* close connection */
$mysqli->close();
If facing problem with out_param, use select to return last insert id as result.
BEGIN
DECLARE last_id INT DEFAULT 0;
INSERT INTO test (name, email) VALUES ('value1', 'value2');
SET last_id = LAST_INSERT_ID();
SELECT last_id;
END
EDIT 2 :
If you are facing problem in retrieving Stored Procedure result set use following code -
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
To access the out param use follwing code -
// execute the stored Procedure
// #uid - IN param, #userCount - OUT param
$result = $connect->query('call IsUserPresent(#uid, #userCount)');
// getting the value of the OUT parameter
$r = $connect->query('SELECT #userCount as userCount');
$row = $r->fetch_assoc();
$toRet = ($row['userCount'] != 0);
insert_id is a property of mysqli class, while you are trying to get it from a statement object.
inside SP you can set like this outParam = LAST_INSERT_ID();
LAST_INSERT_ID() returns the most recently generated ID is maintained in the server on a per-connection basis.
the following returns false and i don't know how to find out what exactly is wrong.
$stmt = $dbo->stmt_init();
if($stmt->prepare("INSERT INTO transactions ('id', 'time') VALUES ('',?)")) // returns false
{
}
i have another statement which does an select open at that time. is it a problem to have more than one statements?
Have you verified that you are connecting to the database successfully?
/* check connection */
if ( mysqli_connect_errno() ) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
As far as figuring out what's wrong with your prepared statement, you should be able to display $stmt->error, which will return a string description of the latest statement error, and $dbo->error, which will return the latest mysqli error.
printf("Error: %s.\n", $stmt->error);
You don't want single quotes around your table names. It should look like this:
$stmt = $dbo->stmt_init();
if($stmt->prepare("INSERT INTO transactions (id, time) VALUES ('', ?)")) {
}
just check whether those columns are properly entered... as i was getting same error coz i mentioned non existing column name in the query..
$query = "INSERT INTO users (name, password) VALUES ('$myusername', '$mypassword')";
if (!($result = $mysqli->query($query)))
die("WHAT???? " . $mysqli->error . " EEEEEFFFFFFF.");
$count = $result->num_rows;
while ($row = $result->fetch_array()) {
if ($row[name] == $myusername) {
$mysqli->query("DELETE FROM users WHERE name='$myusername' AND password='$mypassword'");
$count = 5;
}
}
When I run this, it gives me an error:
Fatal error: Call to a member function fetch_array() on a non-object in /home/appstore/public_html/phpstoof/signedup.php on line 26
Where line 26 is where the while statement starts (while(x)). $mysqli ALREADY an instance of mysqli(). I don't see the how this is an error if the same code works on another file.
An INSERT statement has nothing to fetch.
As #mellamokb says, INSERT has nothing to fetch. Also you have used a mix of MySQL and MySQLi.
With MySQLi, the code should be like:
$mysqli = new mysqli($db_host, $db_username, $db_password, $db_database);
$str_sql = 'INSERT INTO users (name, password) VALUES (?, ?)';
// Create a prepared statement
$stmt = $mysqli->prepare($str_sql);
// Bind parameters for markers; same order and same count in prepared statement
$stmt->bind_param('ss', $myusername, $mypassword);
// Execute query
$stmt->execute();
// *************************************************************************
// If you're using a SELECT statement, each output field must be bound to
// a variable in the same order as in SELECT
// Bind result variables
$stmt->bind_result($_var1, $_var2, $_var3, ...);
// Fetch results and generate output as an associative array
while ($stmt->fetch())
{
// Handle $_var1, $_var2, $_var3, ...
}
// *************************************************************************
// Free stored result memory
$stmt->free_result();
// Close statement
$stmt->close();
// Close connection
$mysqli->close();