First off, this question has been asked before but my code style is a bit different than those in the previous questions.
I have MSSQL server and I use PHP to insert into my database.
This works.
I just need to get the last inserted ID after it has been inserted.
So this is my code:
$email=str_replace("'","''", $_POST['email']);
$password=str_replace("'","''", $_POST['password']);
$query="INSERT INTO Profiles(";
$query=$query."VP_Email,";
$query=$query."VP_Password";
$query=$query.") VALUES (?,?) SELECT SCOPE_IDENTITY() AS ins_id";
$stmt = sqlsrv_prepare($conn, $query, array(&$email, &$password));
$result = sqlsrv_execute($stmt);
if (!$result) {
echo "error: Insert Error";
exit;
} else {
sqlsrv_next_result($stmt);
sqlsrv_fetch($stmt);
$Profileid = sqlsrv_get_field($stmt,0);
}
echo $Profileid;
When i run my code, the data gets inserted into the database but the $Profileid is always empty!
Could someone please advice on this issue?
Thanks in advance.
Related
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'm inserting into an Access database via PHP but I'm struggling to get the ID of the last inserted row. I have had this working previously but our server broke and I've had to re-write it, but it doesn't return - I'm sure this is how I did it:
$idquery = "select ##IDENTITY from [Businesses]";
try{
$rs = $conn->execute($query);
$idReturned = $conn->execute($idquery);
echo json_encode($idReturned);
} catch(com_exception $e){
echo($e);
}
The insert is successful but the json_encode($idReturned); is blank, any idea why?
Are you using PDO?
If you are, you can do the following:
$id = $con->lastInsertId();
<?php
// Assume $dbh connection handle is already established
$sql = "INSERT INTO business (name) VALUES ('BUS')";
$sth = $dbh->prepare($sql);
$sth->execute();
$lastId = $dbh->lastInsertId(); //This is where you get last inserted ID
?>
Depends on the DB provider, there might be a situation that you need to set the "Primary key" for that table
i have a register form and I tried to insert information into multiple tables but that second query doesn't work , i know i have to use user_id for second one but can someone explain to me how?
$sql="INSERT INTO users(firstname,lastname,email,password) VALUES('$firstname','$lastname','$email','$password')";
$sql2="INSERT INTO address(phone,city,address) VALUES('$phone','$city','$address')";
$result=mysql_query($sql);
if($result){
echo "Account Successfully Created";
} else {
echo "Failure!";
}
A quick/dodgy solution would be:
$sql="INSERT INTO users(firstname,lastname,email,password) VALUES('$firstname','$lastname','$email','$password')";
$result = mysql_query($sql);
if($result){
$userid = mysql_insert_id();
$sql2="INSERT INTO address(userid, phone,city,address) VALUES($userid, '$phone','$city','$address')";
$result = mysql_query($sql2);
}
You should use the newer mysql functions though - mysqli
http://php.net/manual/en/book.mysqli.php as mysql is deprecated.
If you decide to stick with mysql though - at the very least mysql_real_escape those values :)
I'm currently trying to make a page via php which allows the user to update data in my database. I'm experiencing two problems: first when I run my code I get the "Error: Query was empty", however updates were made to the database and this leads me to my second problem. Fields that were left empty (a user doesn't have to enter data into all the fields if they only have one or two things to update) become blank after the updates are made. This is because my current script updates all elements, but is there any way I can have it where if the user leaves an input field blank, nothing gets changed when the database is updated?
Here is my code:
if (isset($_POST['submit'])) {
$id = $_POST['id'];
$lastname = $_POST['lastname'];
$firstname = $_POST['firstname'];
$color = $_POST['color'];
$number = $_POST['number'];
// need id to be filled and need at least one other content type for changes to be made
if (empty($id) || empty($lastname) and empty($firstname) and empty($major) and empty($gpa)) {
echo "<font color='red'>Invalid Submission. Make sure you have an ID and at least one other field filled. </font><br/>";
} else {
// if all the fields are filled (not empty)
// insert data to database
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
// display success message
echo "<font color='blue'>Data updated successfully.</font>";
// Close connection to the database
mysql_close($con);
}
}
To answer your question, you need to catch the query's result and check for errors on that.
$query = mysql_query(/*query*/);
if (!$query)
//error handling
Be sure to read up on SQL injections, as per my comment.
To better help you understand the behavior you were seeing, I will explain to you what was wrong with your code:
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
That first part was executing a MySQL query, regardless of that fact that you did not assign it's return value to a variable.
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
The second part was attempting to run a query by passing the first parameter $sql which has not been set, and the second parameter $con which also appears to not have been set. The first query you ran executed just fine while the second one could never execute. Your solution:
$result = mysql_query(
"UPDATE students
SET lastname = '$lastname', firstname = '$firstname',
favoritecolor = '$color', favoritenumber = '$number'
WHERE id = '$id'"
);
if (!$result) {
throw new Exception('Error: ' . mysql_error());
// or die() is fine too if that's what you really prefer
}
if (!mysql_query($sql,$con)) Here $sql and $con are not defined. Should you be running mysql_query twice?
Few guesses:
There is no mysql connect function I assume it's called elsewhere
Print out your query string. I've always found explicitly denoting what is a string and what is a variable by 'SELECT * FROM '.%tblvar.';'; to be much more debug friendly.
I have the following table:
ID: bigint autoinc
NAME: varchar(255)
DESCRIPTION: text
ENTRYDATE: date
I am trying to insert a row into the table. It executes without error but nothing gets inserted in database.
try {
$query = "INSERT INTO mytable (NAME, DESCRIPTION, ENTRYDATE) VALUES(?,?,?)";
$stmt = $conn->prepare($query);
$name= 'something';
$desc = 'something';
$curdate = "CURDATE()";
$stmt->bind_param("sss", $name, $desc, $curdate);
$stmt->execute();
$stmt->close();
$conn->close();
//redirect to success page
}
catch(Exception $e) {
print $e;
}
It runs fine and redirects to success page but nothing can be found inside the table. Why isn't it working?
What about replacing DESCTIPTION with DESCRIPTION inside the $query?
Edit
Just out of curiosity, I created a table called mytable and copy-pasted your code into a PHP script.
Here everything worked fine and rows got inserted, except that the binded parameter CURDATE() did not execute properly and the ENTRYDATE cell was assigned 0000-00-00.
Are you sure you are monitoring the same database and table your script is supposedly inserting to?
What happens when going with error_reporting(E_ALL); ?
Have you verified that the script actually completes the insertion?
The following appears to be working as expected:
error_reporting(E_ALL);
try {
$query = "INSERT INTO mytable (NAME, DESCRIPTION, ENTRYDATE) VALUES (?, ?, CURDATE())";
$stmt = $conn->prepare($query);
$name= 'something';
$desc = 'something';
$stmt->bind_param("ss", $name, $desc);
$stmt->execute();
if ($conn->affected_rows < 1) {
throw new Exception('Nothing was inserted!');
}
$stmt->close();
$conn->close();
//redirect to success page
}
catch(Exception $e) {
print $e->getMessage();
}
Are you sure there is no error? There seems to be a typo in your column name for example.
Note that PDO is extremely secretive about errors by default.
See How to squeeze error message out of PDO? on how to fix this.
Try preparing this query instead:
"INSERT INTO mytable (NAME, DESCRIPTION, ENTRYDATE) VALUES(?,?,CUR_DATE())"
And check the results of $stmt->execute(). It would have given you a warning that "CUR_DATE()" (sic) is not a valid DATE.
You can check if a statement was correctly executed by checking the return value of execute() and querying the errorInfo() method:
if (!$stmt->execute()) {
throw new Exception($stmt->errorInfo(), stmt->errorCode());
}
Be aware that upon failure, execute() does not throw an exception automagically. You'll have to check for successful operation and failure for yourself.
Is it possible that autocommit is OFF?
If so then you have to commit your insert like so
/* commit transaction */
$conn->commit();
Regards