SQLite: last_insert_rowid() in same INSERT statement - php

I running this query in PHP/SQLite 3 (PDO)
Scenario: a new driver is inserted into drivers table and an existing car is immediately linked to him:
DRIVERS
driver_id [PK]
driver_name
CARS
car_id [PK]
fk_driver_id [FK]
$qr = "INSERT INTO drivers (driver_name) VALUES ('{$_GET['driver_name']}'); COMMIT; UPDATE cars SET fk_driver_id=( SELECT last_insert_rowid() ) WHERE car_id={$_GET['car_id']};";
$stmt = $dbh->prepare($qr);
$result = $stmt->execute();
It inserts the driver but does not UPDATE the cars table and produces no error either.
It works if I use the same query using SQLite Spy.
In PHP it will only if I break it in two parts:
$qr = "INSERT INTO drivers (driver_name) VALUES ('{$_GET['driver_name']}'); COMMIT; ";
$stmt = $dbh->prepare($qr);
$result = $stmt->execute();
$qr = "UPDATE cars SET fk_driver_id=( SELECT last_insert_rowid() ) WHERE car_id={$_GET['car_id']};";
$stmt = $dbh->prepare($qr);
$result = $stmt->execute();
What is wrong in the PHP code if it won't work in one single statement?

Try this way :
$qr = "INSERT INTO drivers (driver_name) VALUES ('{$_GET['driver_name']}'); ";
$stmt = $dbh->prepare($qr);
$result = $stmt->execute();
$lastId = $dbh->lastInsertId();
$dbh->commit();
$qr = "UPDATE cars SET fk_driver_id=? WHERE car_id={$_GET['car_id']};";
$stmt = $dbh->prepare($qr);
$result = $stmt->execute(array($lastId));

Related

PDO fetch not working with INSERT, UPDATE then SELECT query [duplicate]

This question already has answers here:
PDO multiple queries
(1 answer)
PDO Transaction statement with insert and fetch output error
(1 answer)
Closed 1 year ago.
$sql = "INSERT INTO book (bookname) values('kkkkkkkkk');
SET #bookid = LAST_INSERT_ID();
INSERT INTO paper (papername) values('hhhhhhh');
SET #paperid = LAST_INSERT_ID();
UPDATE author SET bookid = #bookid, paperid = #paperid WHERE id = 11;
SELECT #bookid as bookid, #paperid as paperid FROM DUAL;"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();
$numofnewParn =$stmt->rowCount();
if($numofnewParn>0){
$newParentDt = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($newParentDt);
}
I have set of inserts with LAST_INSERT_ID assigned to respective parameters.
Later, updating a table with the parameters.
until $stmt->execute(); is not problem.
My question is can I continue the query by adding SELECT and fetch the data like $stmt->fetch(PDO::FETCH_ASSOC)?
or does it not make sense? if so, is there any source?
because above code does not print out.
You need to use PDOStatement::nextRowset see here to move onto the next queries result in your multi statement... however a cleaner setup would be to break this down into single statement queries and use PHP variables to save your bookid and paperid values:
<?php
$sql = "INSERT INTO book (bookname) values('kkkkkkkkk');"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();
$bookid = $pdoConnect->lastInsertId();
$sql = "INSERT INTO paper (papername) values('hhhhhhh');"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();
$paperID = $pdoConnect->lastInsertId();
$sql = "UPDATE author SET bookid = $bookid, paperid = $paperid WHERE id = 11;"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();

Php: fetching last inserted row on mysql table to use for another mysql statement

I need to fetch the id of the last inserted row from a mysql table using php and use that id to enter a new entry on another table. I have this until now
$inductionmethod = $_POST['inductionmethod'];
$injectionmethod = $_POST['injectionmethod'];
$dosage = $_POST['dosage'];
$metric = $_POST['metric'];
$notes = $_POST['notes'];
global $db_usr;
$query = "SELECT MAX( experiment_id ) FROM experiment";
$prep = $db_usr->prepare($query);
$lastid = $prep->fetch();
$query ="INSERT INTO experiment_using_methods (experiment_id, induction_method, injection_method, dosage_quantity, dosage_unit, dosage_qualitative)
VALUES (
'".$lastid['MAX( experiment_id )']."', # the fetched ID of the corresponding dataset
(SELECT induction_method_id FROM induction_method WHERE im_name = '".$inductionmethod."'), # name of induction method
(SELECT injection_method_id FROM injection_method WHERE im_name = '".$injectionmethod."'), # name of the injection method
'".floatval($dosage)."', # dosage quantity
'".$metric."', # dosage unit or metric
'".$notes."' # qualitative dosage - REMOVE??
)";
$prep = $db_usr->prepare($query);
$prep->execute();
I think I'm getting an error while fetching the MAX( experiment_id) or maybe I'm using it incorrectly on the INSERT statement because if I replace the ".$lastid['MAX( experiment_id )']." part by a number the insert statement works fine. On the other hand I also test the SELECT MAX( experiment_id ) FROM experiment statement on the mysql command line and it also works fine. Am I using fetch and referencing the result value correctly?
Thing this is the main issue:
$prep = $db_usr->prepare($query);
$lastid = $prep->fetch();
change it to:
$prep = $db_usr->prepare($query);
$prep->execute();
$lastid = $prep->fetch();
If you have connection as $con, then for MySQLi Object-oriented:
if ($con->query($sql) === TRUE) {
$last_id = $conn->insert_id;
}
MySQLi Procedural way:
if (mysqli_query($con, $sql)) {
$last_id = mysqli_insert_id($con);
}
PDO way:
$con->exec($sql);
$last_id = $con->lastInsertId();

Select table from Sql server and insert data to Mysql table

I have a running ms sql server and want some data copied to a mysql database.
i already can connect to them both so i made something like:
$pdo = new PDO('SQLSERVER', $user, $password);
$sql = "SELECT id, name FROM users";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$json_users = array();
while ($row = $stmt->fetchObject()){
$json_users[] = $row;
}
$pdo = new PDO('MYSQLDB', $user, $password);
foreach ($json_users as $key => $value){
$sql = "INSERT INTO users (id, name) VALUES (:id, :name)"
$stmt = $pdo->prepare($sql);
$stmt->bindParam('id', $value->id, PDO::PARAM_INT);
$stmt->bindParam('name', $value->name, PDO::PARAM_STR);
$stmt->execute();
}
this does work but takes a lot of time cause its a big table.
so my question is can i insert the complete results from sqlserver to mysql at once with only one insert query? without the foreach?
Update: the table contains 173398 rows and 10 columns
With prepared statements (especially for multi-insert) you want to have your prepared statement outside your loop. You only need to set the query up once, then supply your data in each subsequent call
$sql = "INSERT INTO users (id, name) VALUES (:id, :name)";
$stmt = $pdo->prepare($sql);
foreach($json_users as $key => $value){
$stmt->bindParam('id', $value->id, PDO::PARAM_INT);
$stmt->bindParam('name', $value->name, PDO::PARAM_STR);
$stmt->execute();
}
You can export this into CSV file first from MSSQL then import that file into MySQL.
$pdo = new PDO('SQLSERVER', $user, $password);
$sql = "SELECT id, name FROM users";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$fp = fopen('/tmp/mssql.export.csv', 'w');
while ($row = $stmt->fetch(PDO::FETCH_NUM)){
fputcsv($fp, array_values($row));
}
fclose($fp);
$pdo = new PDO('MYSQLDB', $user, $password, array(PDO::MYSQL_ATTR_LOCAL_INFILE => 1));
$sql = <<<eof
LOAD DATA LOCAL INFILE '/tmp/mssql.export.csv'
INTO TABLE user_copy
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(id,name)
eof;
$pdo->exec($sql);
one drawback with the above, you need to have this configuration enabled in my.cnf ( MySQL configuration )
[server]
local-infile=1
Since MySQL cannot read files that are owned by others unless it it opened with --local-infile=1
I would suggest not bind values, but generate the query string:
$sql = "";
foreach ($json_users as $key => $value){
if ($sql=="") {
$sql = "INSERT INTO users (id, name) VALUES ";
$sql =." (".$value->id.',"'.$value->name.'")';
} else {
$sql .= ", (".$value->id.',"'.$value->name.'")';
}
}
$stmt = $pdo->prepare($sql);
$stmt->execute();
It is not best practice, but since you trust data source it could help.
Consider doing bulk inserts instead of one row at a time.
$sourcedb = new \PDO('SQLSERVER', $sourceUser, $sourcePassword);
$targetdb = new \PDO('MYSQLDB', $targetUser, $targetPassword);
$sourceCountSql = "SELECT count(*) count FROM users;";
/**
* for mssql server 2005+
*/
$sourceSelectSql = "
SELECT
id,
name
FROM
(
SELECT
ROW_NUMBER() OVER (ORDER BY id) RowNum,
id,
name
FROM
users
) users
WHERE
RowNum >= %d
AND RowNum < %d
ORDER BY
RowNum
";
/**
* for mssql server 2012+
*/
$sourceSelectSql = "
SELECT
FROM TableName ORDER BY id OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY;
SELECT
id,
name
FROM
users
ORDER BY
id
OFFSET %d ROWS
FETCH NEXT %d ROWS ONLY
";
$sourceCount = $sourcedb->query($sourceCountSql, \PDO::FETCH_COLUMN, 0);
$rowCount = 1000;
$count = 0;
$count2 = 0;
for($x = 0; $x < $sourceCount; $x += $rowCount) {
$sourceRecords = $sourcedb->query(sprintf($sourceSelectSql, $x, $rowCount), \PDO::FETCH_ASSOC);
$inserts = [];
foreach($sourceRecords as $row) {
$inserts[] = sprintf("(:id_%1$d, :name_%1$d)", $count++);
}
$stmt = $targetdb->prepare(sprintf("INSERT INTO users (id, name) VALUES %s;", implode(',', $inserts));
foreach($sourceRecords as $row) {
$stmt->bindParam(sprintf('id_%d', $count2), $row['id'], \PDO::PARAM_INT);
$stmt->bindParam(sprintf('name_%d', $count2), $row['name'], \PDO::PARAM_STR);
$count2++;
}
$targetdb->execute();
unset($inserts);
}

SQL insert into select issue

So i think i'm close to figuring this out but my query won't add the item from the "pending" table to the "items" table. can you guys help me out with this please. Also if i want it to delete after it gets added should i add the code below the INSERT INTO SELECT query? thanks
action.php:
$sql = "INSERT INTO items (photo,title,description, name) SELECT (photo,title,description, name) FROM pending";
$stmt = $conn->prepare($sql);
$stmt->execute();
Example for delete query after it takes the item from the "pending" into items:
$idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT);
//try deleting record using the record ID we received from POST
$sql = "DELETE FROM pending WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $idToDelete, PDO::PARAM_INT);
$stmt->execute();
I think you are leaving yourself open to mistakes doing it this way.
Consider what would happen if a new row is added to the pending queue after you have issued the INSERT SELECT but before you have started your delete.
I think you need to do this in a more controlled way inside a single loop to make sure you are only deleting what you have copied from pending into items.
$sql = "SELECT photo,title,description, name FROM pending";
$select_pending = $conn->prepare($sql);
$select_pending->execute();
$sql = "INSERT INTO items (photo,title,description, name)
VALUES (:photo,:title,:description, :name)";
$insert_items = $conn->prepare($sql);
$sql = "DELETE FROM pending WHERE id = :id";
$delete_pending = $conn->prepare($sql);
// only if you are using INNODB databases.
//$conn->beginTransaction();
while( $row = $select_pending->fetch_object() ) {
$insert_items->bindParam(':photo', $row->photo, PDO::PARAM_STR);
$insert_items->bindParam(':title', $row->title, PDO::PARAM_STR);
$insert_items->bindParam(':description', $row->description, PDO::PARAM_STR);
$insert_items->bindParam(':name', $row->name, PDO::PARAM_STR);
$insert_items->execute();
$delete_pending->bind_param(':id', $row->id, PDO::PARAM_INT);
$delete_pending->execute();
}
// only if you are using INNODB databases.
//$conn->commit();
$sql = "INSERT INTO items (photo,title,description, name)
SELECT photo,title,description, name FROM pending";
remove the () in the SELECT statement.

How can I properly use a PDO object for a parameterized SELECT query

I've tried following the PHP.net instructions for doing SELECT queries but I am not sure the best way to go about doing this.
I would like to use a parameterized SELECT query, if possible, to return the ID in a table where the name field matches the parameter. This should return one ID because it will be unique.
I would then like to use that ID for an INSERT into another table, so I will need to determine if it was successful or not.
I also read that you can prepare the queries for reuse but I wasn't sure how this helps.
You select data like this:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
You insert in the same way:
$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));
I recommend that you configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $db object:
$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I've been working with PDO lately and the answer above is completely right, but I just wanted to document that the following works as well.
$nametosearch = "Tobias";
$conn = new PDO("server", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT `id` from `tablename` WHERE `name` = :name");
$sth->bindParam(':name', $nametosearch);
// Or sth->bindParam(':name', $_POST['namefromform']); depending on application
$sth->execute();
You can use the bindParam or bindValue methods to help prepare your statement.
It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name)); Especially if you are binding multiple values/variables.
Check the clear, easy to read example below:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
If you are expecting multiple rows remove the LIMIT 1 and change the fetch method into fetchAll:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetchAll(PDO::FETCH_ASSOC);
//$check will now hold an array of returned rows.
//let's say we need the second result, i.e. index of 1
$row_id = $check[1]['id'];
// do something
}
A litle bit complete answer is here with all ready for use:
$sql = "SELECT `username` FROM `users` WHERE `id` = :id";
$q = $dbh->prepare($sql);
$q->execute(array(':id' => "4"));
$done= $q->fetch();
echo $done[0];
Here $dbh is PDO db connecter, and based on id from table users we've get the username using fetch();
I hope this help someone, Enjoy!
Method 1:USE PDO query method
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Getting Row Count
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';
Method 2: Statements With Parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->execute(array($name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Method 3:Bind parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
**bind with named parameters**
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
or
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->execute(array(':name' => $name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Want to know more look at this link
if you are using inline coding in single page and not using oops than go with this full example, it will sure help
//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw);
//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";
//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);
//view the entire array (for testing)
print_r($result);
//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}

Categories