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
Related
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.
I need to get the last inserted ID for each insert operation and put it into array, I am trying to see what is the correct way of doing it.
Following this post Which is correct way to get last inserted id in mysqli prepared statements procedural style?
I have tried to apply it to my code but I am still not getting the right response.
if($data->edit_flag == 'ADDED')
{
$rowdata[0] = $data->location_name;
$rowdata[1] = 0;
$rowdata[2] = $data->store_id;
$query = "INSERT IGNORE INTO store_locations (location_name,total_items, store_id) VALUES (?,?,?)";
$statement = $conn->prepare($query);
$statement->execute($rowdata);
$id = mysqli_stmt_insert_id($statement);
echo "inserted id: " . $id;
}
I then realised that I am using a PDO connection so obviously mysqli functions wont work. I went ahead and tried the following
$id = $conn->lastInsertId();
echo "insert id: " . $id;
but the response is still empty? What am I doing incorrectly? For the lastInsertId(), should I be using $conn or $statement from here:
$statement = $conn->prepare($query);
$statement->execute($rowdata);
You are using lastInsertId() correctly according to the PDO:lastInsertId() documentation
$statement = $conn->prepare($query);
$statement->execute($rowdata);
$id = $conn->lastInsertId();
Some potential reasons why it is not working:
Is this code within a TRANSACTION? If so, you need to COMMIT the transaction after the execute and before the lastInsertId()
Since you INSERT IGNORE there is the potential that the INSERT statement is generating an error and not inserting a row so lastInsertId() could potentially be empty.
Hope this helps!
If you are using pdo,
$stmt = $db->prepare("...");
$stmt->execute();
$lastInsId = $db->lastInsertId();
I have a script which is containing some queries:
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
// inserting
$stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
$stm1->execute(array($value));
// updating
$stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
$stm2->execute(array($id));
As you see there is two statements (insert and update). All I'm trying to do is making sure both of them work or none of them.
I mean I want to implement a dependency between those two statements. If updating fails, then inserting shouldn't work and vice versa. How can I do that?
You could use sql transactions
http://www.sqlteam.com/article/introduction-to-transactions
You can use transactions and PDO has an api for this (http://php.net/manual/en/pdo.begintransaction.php),
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
try{
$db_conn->beginTransaction();
// inserting
$stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
$stm1->execute(array($value));
// updating
$stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
$stm2->execute(array($id));
$db_conn->commit();
}
catch(PDOException $e){
$db_conn->rollBack();
}
As others said, you could use 'transactions'.
Or
you could mannualy check whether the data is right in the database. Just 'select' what you have inserted.
The 'execute' function return 'true' on success or 'false' on failure. You can do something like:
$isDone=$stm1->execute(array($value));
if(!$isDone){
echo 'Operation fails, I will stop.';
return false;
}
I'm trying to update MySQL table recored by any calculated form values in php, but it doesn't work. May you help me please thank you.
You should use mysqli with prepared statements, like so.
I hope this is enough for you, you gave me nothing to work with so...
<?php
//Get the form value and ID of the database record to update
$value = $_POST['value']; // Value submitted by a form element (replace this with whatever you want to change)
$id = $_POST['id']; //ID, could be of the user etc. (this will be a primary key inside the database) (does not have to be submitted via POST, I assume you know this already)
//Establish a new mysql connection
$mysqli = new mysqli($db_host,$db_user,$db_pass,$db_name);
//Set up a query
$query = "UPDATE table SET column_one=? WHERE id=?";
//Prepare the statement
$stmt = $mysqli->prepare($query);
//Bind the parameters
// 'si' = in the order of submitted valurs (column_one=? and id=?) (column_one is s and id is i, s is for string, i is for integer) (this defines what types of variables we are sending)
$stmt->bind_param('si', $value, $id);
//Execute the query
if($stmt->execute()){
//Get the amount of affected rows
$affected = $stmt->affected_rows(); //Should only be 1, but if your ID or whatever you're using to define which parts of the DB to update is not unique, then it can go higher ofc.
//Show success
echo "Database updated, $affected rows affected";
}else{
//Show error
echo "Error, say that this is shown, on stack overflow, as there's obviously something wrong.";
}
//Close the stmt/mysqli stuff
$stmt->close();
$mysqli->close();
I'm trying to do a simple operation on a MySQL database: my contacts have their complete names on a column called first_name while the column last_name is empty.
So I want to take what's on the first_name column and split it on the first occurrence of a white space and put the first part on the first_name column and the second part on the last_name column.
I use the following code but it's not working:
$connection = new mysqli(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME, DATABASE_PORT);
$statement = $connection->prepare("SELECT id, first_name FROM contacts");
$statement->execute();
$statement->bind_result($row->id, $row->firstName);
while ($statement->fetch()) {
$names = separateNames($row->firstName);
$connection->query('UPDATE contacts SET first_name="'.$names[0].'", last_name="'.$names[1].'" WHERE id='.$row->id);
}
$statement->free_result();
$statement->close();
$connection->close();
Can I use the $connection->query while having the statement open?
Best regards.
UPDATE
The $connection->query(...) returns FALSE and I get the following error:
PHP Fatal error: Uncaught exception 'Exception' with message 'MySQL Error - 2014 : Commands out of sync; you can't run this command now'
I changed the code to the following and worked:
$connection = new mysqli(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME, DATABASE_PORT);
$result = $connection->query("SELECT id, first_name FROM contacts");
while ($row = $result->fetch_row()) {
$names = separateNames($row[1]);
$connection->query('UPDATE contacts SET first_name="'.$names[0].'", last_name="'.$names[1].'" WHERE id='.$row[0]);
}
$connection->close();
Can I use the $connection->query while having the statement open?
Yes. It will return a new result object or just a boolean depending on the SQL query, see http://php.net/mysqli_query - In your case of running an UPDATE query it will always return a boolean, FALSE if it failed, TRUE if it worked.
BTW, the Mysqli connection object is not the Mysqli statement object, so they normally do not interfere with each other (disconnecting might destroy/break some statements under circumstances, but I would consider this an edge-case for your question you can ignore for the moment).
I wonder why you ask actually. Maybe you should improve the way you do trouble-shooting?
I can only have one active statement at a given time, so I had to make one of the queries via the $connection->query() method.
As #hakre mentioned:
I still keep my suggestion that you should (must!) do prepared statements instead of query() to properly encode the update values
I opted to use the statement method for the update query, so the final working code is the following:
$connection = new mysqli(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME, DATABASE_PORT);
$result = $connection->query("SELECT id, first_name FROM contacts");
$statement = $connection->prepare("UPDATE contacts SET first_name=?, last_name=? WHERE id=?");
while ($row = $result->fetch_row()) {
$names = separateNames($row[1]);
$statement->bind_param('ssi', $names[0], $names[1], $row[0]);
throwExceptionOnMySQLStatementError($statement, "Could not bind parameters", $logger);
$statement->execute();
throwExceptionOnMySQLStatementError($statement, "Could not execute", $logger);
}
$statement->free_result();
$statement->close();
$connection->close();
Thanks to all that gave their inputs, specially to #hakre that helped me to reach this final solution.