I want to apply transactions but only for this request.is it any impact on insert , update on other table by other users at same.
$conn = ConnectionManager::get('default');
$conn->begin();
try{
//code here
$conn->commit()
}catch(\Exception){
$conn->rollback()
}
unset($conn);
Related
I have this code to insert data from a CSV file to the database. Since, the CSV might have thousands of records, I am trying to implement a batch insert as follows.
$this->_connection->beginTransaction();
$sql = "INSERT INTO dbtable (col1,col2) VALUES (:value1,:value2)";
$stmt = $this->_connection->prepare($sql);
foreach ($requestArray['csv'] as $data) {
$stmt->bindParam(':value1', $data['csvCol1']);
$stmt->bindParam(':value2', $data['csvCol2']);
$stmt->execute();
}
$this->_connection->commit();
The variable $requestArray['csv'], holds all the record of the CSV post request. This code seems to be working as it should. Though, I am trying to improve it, because I want to let the user know how many records failed to insert on the database and if it is possible to show which records failed. Assume a duplicate key, or invalid data or generally any error that might come from this procedure.
PDOStatement::execute() will return false on failure:
$this->_connection->beginTransaction();
$sql = "INSERT INTO dbtable (col1,col2) VALUES (:value1,:value2)";
$stmt = $this->_connection->prepare($sql);
foreach ($requestArray['csv'] as $data) {
$stmt->bindParam(':value1', $data['csvCol1']);
$stmt->bindParam(':value2', $data['csvCol2']);
if (!$stmt->execute()) {
// error processing goes here.
}
}
$this->_connection->commit();
i made login_history table with fields user_id foreign for users table , ip_address and created_at i need to very time to login user save it in login_history table now i'm using
Listeners or last_login users using laravel 5.2 with this code
public function handle(Login $event)
{
$user = \Auth::user();
$data = new LoginHistory();
$event->user->$data->user_id = $user->id;
$event->user->$data->created_at = Carbon::now();
$event->user->$data->ip_address = Request::getClientIp();
$event->user->$data->save();
}
**but this not i want
please any one can help for changing this code i have model created
class LoginHistory extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
and i get this error
Cannot use Illuminate\Foundation\Auth\User as User because the name is
already in use
thanks
Considering you have a Model for the LoginHistory pivot table. In any controller method, you can use the following code.
$user = auth()->user();
LoginHistory::create(['user_id'=>$user->id,'ip_address' => Request::getClientIp(), 'created_at'=>Carbon::now()]);
And if you don't have the model, you can use the DB facade to do the same.
You can create a Middleware in laravel in handle method you can insert the data
$event->user->$data->ip_address = \Request::ip(),
Basically, I have a mysql database where every time I get a row, I want to delete it from the database (after reading its information).
I know I could do something like
$result = mysql_query(" SELECT <some row> FROM table ");
$row = mysql_fetch_array($result);
$id = $row["id"];
mysqli_query(" DELETE FROM table WHERE id=$id");
but now it seems I have two queries going on. Is there a command to tell mysql that I want the row deleted as soon as it gives me the information? I imagine that'd save time and resources.
In my head, it looks like
$result = mysql_query(" SELECT <some row> FROM table THEN DELETE ");
EDIT additional information: I wish to use the SELECTed information after deleting the row. To put it simply, I only want one instance of the information to exist at any give time; it would be as if I were only "moving" a physical copy of the information, so that when it is put on a device/what have you, it is no longer in the table since there is only one copy.
Sorry if my understanding of mysql is rough -- I'm pretty new to it :P
I don't know why you need it but you can use a stored procedure for that:
DELIMITER $$
CREATE PROCEDURE select_and_delete(IN aid INT)
BEGIN
SELECT * FROM table1 WHERE id = aid;
DELETE FROM table1 WHERE id = aid;
END$$
DELIMITER ;
Here is SQLFiddle demo.
mysql_* extension is deprecated, therefore use prepared statements and mysqli or PDO.
Your php code using PDO might look like
$id = 1;
try {
$db = new PDO('mysql:host=localhost;dbname=test;charset=UTF8', 'user', 'userpwd');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = $db->prepare("CALL select_and_delete(?)");
$query->execute(array($id));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo "Exception: " .$e->getMessage();
$result = false;
}
$query = null;
$db = null;
//do whatever you need to do with your resultset
var_dump($result);
Following a rather simplified table structure (with the only column id) presented in SQL Fiddle example if you call it with $id=1 you'll you'll get in $result:
array(1) {
[0]=>
array(1) {
["id"]=>
int(1)
}
}
You'll need to add a timestamp field (with default as CURRENT_TIMESTAMP) to be able to tell when the row was added.
Then you can run the following MySQL query.
DELETE FROM `table` WHERE `timestamp` > DATE_SUB(NOW(), INTERVAL 0 SECOND);
You will need to run this as a cron job though. AFAIK it can't be done in MySQL alone.
I'm in the process of learning CI for myself and this came up. If I run multiple INSERTs, whether as transaction or not, is it possible to get the insert ID of each (in the proper order) instead of running $this->db->insert_id() one at a time for each INSERT?
For example
-- Get ID of each
INSERT INTO table VALUES (insert1), (insert2), (insert3)
-- What if they're called separately
INSERT INTO table VALUES (insert1)
INSERT INTO table VALUES (insert2)
INSERT INTO table VALUES (insert3)
Is it still possible to get the ID as an array from all this?
I think you really must insert it between each inserts as far as i know, just store it in an array.
var $insert_id = array();
public function insert()
{
INSERT INTO table VALUES (insert1)
$this->insert_id =$this->db->insert_id();
INSERT INTO table VALUES (insert2)
$this->insert_id =$this->db->insert_id();
INSERT INTO table VALUES (insert3)
$this->insert_id =$this->db->insert_id();
}
everytime a database record is inserted you can still use insert_id(); after each insert then store it to an array. then you coudl make a function to return it.
public function get_inserted_keys()
{
return $insert_id;
}
It is simple
Controller
$ids = array();
$data[0] = array(blah,blah);
$data[1] = array(blah,blah);
$data[2] = array(blah,blah);
for($i=0;$i<3;$i++)
{
$ids[] = $this->my_model->insert($data[$i]);
}
echo '<pre>';
print_r($ids);
Model
public function insert($data)
{
$this->db->insert('table_name',$data);
return $this->db->insert_id()
}
I have a linq query to insert data in table. but its not working. I saw some example on internet tried to do like that but doesn't seems to work.
Tablename: login has 3 columns userid, username and password. I set userid as autoincrementing in database. So I have to insert only username and password everytime.Here's my code.
linq_testDataContext db = new linq_testDataContext();
login insert = new login();
insert.username = userNameString;
insert.Password = pwdString;
db.logins.Attach(insert);// tried to use Add but my intellisence is not showing me Add.I saw attach but dosent seems to work.
db.SubmitChanges();
have a look on http://www.codeproject.com/KB/linq/LINQToSQLBaseCRUDClass.aspx
linq_testDataContext db = new linq_testDataContext();
login insert = new login();
insert.username = userNameString;
insert.Password = pwdString;
db.logins. InsertOnSubmit(insert);
db.SubmitChanges();
If you Attach - It should attach to the particular object Context .But it wont reflect in database .If you want to insert any values try with InsertOnSubmit(object) and do
SubmitChanges() to save it in database
Attach() is the wrong method, you need to call InsertOnSubmit() to let Linq-To-Sql generate an insert statement for you. Attach() is for distributed scenarios, where your entity has not been retrieved via the same data-context that is used for submitting changes.
linq_testDataContext db = new linq_testDataContext();
login insert = new login();
insert.username = userNameString;
insert.Password = pwdString;
db.logins.InsertOnSubmit(insert);// tried to use Add but my intellisence is not showing me Add.I saw attach but dosent seems to work.
db.SubmitChanges();
Method to save employee details into Database.
Insert, Update & Delete in LINQ C#
Employee objEmp = new Employee();
// fields to be insert
objEmp.EmployeeName = "John";
objEmp.EmployeeAge = 21;
objEmp.EmployeeDesc = "Designer";
objEmp.EmployeeAddress = "Northampton";
objDataContext.Employees.InsertOnSubmit(objEmp);
// executes the commands to implement the changes to the database
objDataContext.SubmitChanges();