I have to INSERT INTO two tables at once, let's say one table is my client_enquiry and another table is the client_materials.
Until here it's okay, the INSERT command it's working in both tables. And If something bad happens when I'm inserting on the second table (client_materials)? How can I "rool back" if the INSERT command fails on table client_materials?
Basically I have this:
$sql_table1 = "INSERT INTO client_enquiry (reference, date) VALUES ('REF', '2013-05-12')";
$q = $conn->prepare($sql_table1);
$q ->execute();
$Last_ID = $conn->lastInsertId('id_enquiry');
$sql_table2 = "INSERT INTO client_materials (id_client_enquiry,description, date)
VALUES (".$Last_ID."'Description', '2013-05-12')";
$q = $conn->prepare($sql_table2);
$q -> execute();
Do the very rollback you mentioned.
$conn->beginTransaction();
try
{
$sql = "INSERT INTO client_enquiry (reference, date) VALUES (?,?)";
$q = $conn->prepare($sql);
$q ->execute(array('REF', '2013-05-12'));
$Last_ID = $conn->lastInsertId();
$sql_table2 = "INSERT INTO client_materials (id_client_enquiry,description, date)
VALUES (?,?,?)";
$q = $conn->prepare($sql);
$q -> execute(array($Last_ID, 'Description', '2013-05-12'));
$conn->commit();
}
catch (PDOException $e)
{
$conn->rollback();
throw $e;
}
You just need to be sure that engine supports transactions and PDO is set into exception throwing mode
Related
Which code do I need to retrieve a single value i from a column from table in SQL?
user_comment_count
This is column name in table
table is :
zmar_hreviews_list_total
This is code I use with error:
<?php
$insert1 ="/// ";
$string = "ars <pre>{$insert1}</pre>";
$query = 'SELECT user_comment_count FROM zmar_hreviews_list_total WHERE contentid = '.$item->getId();
$db->setQuery( $query );
$result = $db->loadResult();
if($result) {
$result = str_replace('*','',$result);
print_r($insert1); print_r($result);
}
?>
try:
select user_comment_count from zmar_hreviews_list_total
I have a query, and I want to get the last ID inserted. The field ID is the primary key and auto incrementing.
I know that I have to use this statement:
LAST_INSERT_ID()
That statement works with a query like this:
$query = "INSERT INTO `cell-place` (ID) VALUES (LAST_INSERT_ID())";
But if I want to get the ID using this statement:
$ID = LAST_INSERT_ID();
I get this error:
Fatal error: Call to undefined function LAST_INSERT_ID()
What am I doing wrong?
That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().
Like:
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();
If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:
$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();
lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass)
VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
Like this $lid = $conn->lastInsertId();
Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php
I've looked all over their docks but they really like to use active records. Can someone please tell me how to do a plain old SQL insert for an INSERT in Codeigniter?
EDIT
And this is for their $this->db object;
It's a good idea to escape your inputs.
$sql = "INSERT INTO `yourtable` VALUES `foo`= ? WHERE `id` = ?";
return $this->db->query($sql, [$bar, $id]);
or for an update
$sql = "UPDATE `yourtable` SET `foo`= ?, `bar` = ? WHERE `id` = ?";
return $this->db->query($sql, [$f, $b, $id]);
Using query:
$this->db->query("INSERT INTO ...");
Using active record:
$data = array(
"attribute" => "value"
);
$this->db->insert("table_name", $data);
References:
https://www.codeigniter.com/userguide2/database/queries.html
https://www.codeigniter.com/userguide2/database/active_record.html
I want to add new record to table1 on SQLite
use SQL::Abstract;
my %data = (
id => \'max(id)', # it is doesn't work so which variant is right?
record => 'Something'
);
my $sql = SQL::Abstract->new;
my ($stmt, #bind) = $sql->insert('table1', \%data);
...
my $sth = $dbh->prepare($stmt);
If I used DBIx::Class in Catalyst app I would written like so:
id => $c->model('Model')->get_column('id')->max()
and it will work fine.
So how can I reach the same aim but using just SQL::Abstract which is used in DBIx::Class as well.
Could someone fixed it? Thanks.
This is a piece of code. As you can see, first you need to get the max id+1 and then do the insert command. I have to notice you this is not safe, because in a multi-(user,process,thread) environment, a second process can execute the same code and get race conditions.
But I assume you are just learning the SQL::Abstract api, and that problem doesn't matter
use DBI;
use SQL::Abstract;
#create table TEST(ID integer, NAME varchar);
my $dbh = DBI->connect('dbi:SQLite:dbname=test.db', '', '', {AutoCommit=>1});
my $sql = SQL::Abstract->new;
my($stmt, #bind) = $sql->select("TEST", [ 'max(ID)+1 as ID' ] );
my $sth = $dbh->prepare($stmt);
$sth->execute(#bind);
my ($id) = $sth->fetchrow_array // 1;
print "Select ID: $id", "\n";
$sth->finish;
($stmt, #bind) = $sql->insert("TEST", { ID=>$id, NAME=>"test-name"} );
$sth = $dbh->prepare($stmt);
$sth->execute(#bind);
$dbh->disconnect;
i have tried to make sql code in CI, the problem is the ID_LABEL at t_publisher is filled with 0 where it should filled with number that taken from t_label..
$sql['query1'] = "INSERT into t_user (USER_NAME, USER_PASS, USER_STATUS, USER_TYPE) values ('$user', '$pass','1','publisher')";
$sql['query2'] = "INSERT INTO t_label (LABEL) values('$user')";
$id_label = "select id_label from t_label where label ='".$user."'";
$id = $this->db->query($id_label)->result();
$sql['query3'] = "INSERT INTO t_publisher (PUBLISHER, ARTIS, ID_LABEL) values('$user', 'Various Artist', '$id')";
$result = array();
foreach($sql as $key => $value){
$result[$key] = $this->db->query($value);
}
please help :)
to get the id_label
try this
$id_result = $this->db->query($id_label);
foreach($id_result->result_array() as $row){
$id=$row['id_label'];
}
$id is returning an object not a single value. Try inserting $id->id_label instead of just $id