I wrote a bot. And it scrapes the data and inserting it into DB. When I run the bot first time there is no problem. But when I run the bot second time error pops. Let me explain what I meant.
Here, I am inserting data into DB.
if (Menu::where("url", "=", $link."menu")->first()) {
$insertedMenuId = count($url);
} else {
$insertedMenuId = Menu::insertGetId($database);
$this->line("Menu Inserted.");
}
Using this $insertedMenuId to insert connected data into another table. But the problem here, if I already inserted the data. Then it's not giving me the ID. And $insertedMenuId being empty. So second piece of code is not starting. Because there is no id given.
I tried to solve the problem by counting the url. If the url is already inserted. But this time it's giving the wrong id.
If the record exists, just use its id.
$row = Menu::where("url", "=", $link."menu")->first()
if ($row) {
$insertedMenuId = $row->id;
} else {
$insertedMenuId = Menu::insertGetId($database);
$this->line("Menu Inserted.");
}
Related
I am using react js and laravel 8. I have inserted a data on pgsql table through API and after inserted i have fetched all data from that table but I am able to get all rows except the last inserted row.
Even simple select query also not fetching all data immediately.
Firstly I have thought that it is react js state issue but when i have mailed the fetch result data then I have seen the same issue.
Here is my code
$insertUserFavouriteID = Cms::insertUserFavouriteByAPI($userID,$dataset_graph_id); // Inserted a data on pgsql table and also returned the fetch data
$sql = "SELECT id FROM favouritetable WHERE user_id = ".$userID;
$result = App::getRows($sql);
if($insertUserFavouriteID) {
#mail("test.rp#gmail.com","My subject", json_encode($result));
return $this->sendResponse($insertUserFavouriteID);
} else {
$error = array();
$error['responseCode'] = '401';
$error['message'] = "Error";
return $this->sendError($error, 401);
}
Can any one please help me why this is happing?
I have a contact list that I made with PHP, jQuery and Datatables, where I have inline editing, and as soon as you click outside of a cell it updates via Ajax. Everything about the update of field values work fine, but now I wanted to save who last updated a record, by saving the username from the current session, so I've done that and sent it to the update file as a $_POST, but it won't save. When I dump it out or echo it, I can see the value, so I know it does get posted, but it just won't save in the database and I can't figure out why.
Since I don't code a lot and have learned what I know by reading and copying stuff from Stackoverflow, I'm sure I'm missing something obvious, but I still need help and I want to learn.
I've tried all kinds of "' variants, and typing in "test" or something in the query or in the variable does save it, so I feel like something is wrong with the $_POST or sql syntax, but since I can dump it and echo it, I have no idea what's wrong.
Worth mentioning is that the first part of the SQL works fine, and updates the cell it's supposed to, so the query runs, but randomly returns either "Uppdaterad!" or "Invaild requests" every other time, but the value saves either way. If I remove the whole "new part" with "last updated by", it works every time and returns "Uppdaterad!" without any problems.
<?php
if(!empty($_POST))
{
// Database settings
include "config.php";
foreach($_POST as $field_name => $val)
{
// Clean post values
$field_contactid = strip_tags(trim($field_name));
$val = strip_tags(trim(mysqli_real_escape_string($con, $val)));
$currentuser = strip_tags(trim(mysqli_real_escape_string($con, $_POST['currentuser'])));
//var_dump($currentuser);
// From the fieldname:contact_id we need to get contact_id
$split_data = explode(':', $field_contactid);
$contact_id = $split_data[1];
$field_name = $split_data[0];
if(!empty($contact_id) && !empty($field_name))
{
// Update the values
mysqli_query($con, "UPDATE contactlist SET $field_name = '$val', `last_updated_by` = '$currentuser' WHERE id = $contact_id") or mysqli_error($con);
//mysqli_query($con, "UPDATE contactlist SET $field_name = '$val' WHERE id = $contact_id") or mysqli_error($con);
echo "Uppdaterad!";
} else {
echo "Invalid Requests";
}
}
} else {
echo "Empty POST!";
}
?>
So i have been pulling my hair out over this for the past two days. I have identified the problem down to this so far:
I am inserting some simple data into the database using Active Record:
if($this->db->insert('table', $data)){
return true;
}
else{
return false;
}
The problem is that it was always returning true whether the data got inserted or not. How i figured this out was that after several failed attempts when the data finally got inserted, the AUTO_INCREMENT ID was at 17, meaning that the insert query was running but failing to insert, hence always returning true. I want to know a reliable method of knowing whether data got inserted or not. Tried:
$this->db->affected_rows() > 0;
as well. But same issue prevails. It returns true.
If you have auto incremental id in your table then check $this->db->insert_id()
if greater the zero or us number then we can say data inserted or
again fire a sql query with id we get and if record exist then data is inserted
but i think that is not necessary just check insert_id
You need to insert your data first and get the result after. You will need to do something like this:
$this->db->insert('my_table', $my_data);
$is_inserted = $this->db->affected_rows() > 0;
if($is_inserted) {
echo 'Yay! Its works!';
} else {
echo 'Something went wrong. No insert ):'
}
You must perform your insert query before get the result. So you will need to run your insert and then get the affected rows. Codeigniter provides the class $this->db that help us to do this very easily. You can even get the inserted id running $this->db->insert_id() instead $this->db->affected_rows() to get the brand new inserted id.
You may find these links useful:
Query Helper Functions -
https://ellislab.com/codeigniter/user-guide/database/helpers.html
Active Record Class
https://ellislab.com/codeigniter/user-guide/database/active_record.html
Good Luck!
i always do this for check data is inserted or not
$this->db->insert('table', $data);
$id = $this->db->insert_id();
if($id)
{
echo "data inserted";
}
else
{
echo "data not inserted";
}
you can also do this also worked for me
$query = $this->db->insert('table', $data);
if($query)
{
echo "data inserted";
}
else
{
echo "data not inserted";
}
This is what I do. It works for me.
$this->db->set($data)->insert($table_name);
if ($this->db->affected_rows()) {
return $this->db->insert_id(); // or return true; in your case
}
return false;
i made a lot of research around here and Google but i cannot find an answer to this problem.
I update a field in a MySQL database with following code:
public function registerPubKey() {
$stmt = $this->cn->prepare('UPDATE sb_user SET pubkey= ? WHERE email= ?');
$exres = $stmt->execute(array($this->info["pubkey"], $this->info["email"]));
if ($exres == false) {
$resultArray["result"] = "Error registering public key";
echo json_encode($resultArray);
exit;
}
$resultArray["result"] = "success";
echo json_encode($resultArray);
}
I'm sure that all works except that the field in the database is empty. I dumped the private variable $info and it contains the pubkey (pubkey is a base64 string).
I noticed that if I change the update query with an INSERT, the value is inserted correctly!
It's likely because you're trying to UPDATE non existent rows. Try adding a ON DUPLICATE KEY before. See INSERT ... ON DUPLICATE KEY UPDATE Syntax. UPDATE returns nothing if the row does not exist.
I ran into a similar issue and validated that:
the row existed, and
the execute parameters were valid and correct
The PDO::errorInfo() function can provide insight into what's actually happening to cause the update to fail:
if (! $stmt->execute($params) ) {
$resultArray["result"] = print_r($stmt->errorInfo(), true);
}
In my case, I got the message The user specified as a definer ('user'#'172.20.%.%') does not exist. Since this was a database snapshot restored to a different subnet, the error message makes sense and the user in-fact did not exist.
I've the following table layout in my database with some data.
I'm taking input by check-boxes so user can select all applicable accident road conditions and it to database. I would say it is okay if you're adding a new record you just loop through the checkboexs checked and insert them in DB
The first information is now saved in the database, now user decided to change the road conditions for any reasons user came back and change it the to the following.
Now my question, how should I update my table. The first thing that came into my mind was to delete the record that were already there and insert the new one's.
My real issue here is, assume user have choose the 3 items before but changed it two or one then how would i delete the those are not checked you know what I'm saying. Below is some code snippets that I've been trying.
$accidentRoadConditions = AccidentRoadConditions::findAccidentRoadConditions($acc_det_id);
$wc_array = [];
while ($roadConditions = $accidentRoadConditions ->fetch(PDO::FETCH_OBJ)) {
$wc_array[] = $roadConditions ->rc_id;
}
Above I'm selecting all the road conditions that is already stored in the database.
if (isset($_POST['rta_ad_rc'])) {
foreach ($_POST['rta_ad_rc'] as $rc_id) {
//AccidentRoadConditions::save(array(null, $ad_lsid, $rc_id));
// $tmprory = AccidentRoadConditions::findByADAndRCIds($acc_det_id, $rc_id);
// if(!$tmprory){
// AccidentRoadConditions::save(array(null, $acc_det_id, $rc_id));
// }
if(in_array($rc_id, $wc_array)){
$errors[] = "in array <br />";
unset($wc_array[0]);
}
}
}
So my question is how to update values in database according to what was checked by user and deleting those which were unchecked which were checked before. Getting bit complicated so simply how to update database according to above mention scenario.
Any Idea?
I think you need to do the following
Store the selected checks in an array
Check in the database if any of those are already saved or not
if yes, skipped them otherwise add them into an array
$old_rc_array = [];
$new_rc_array = [];
while ($roadConditions = $accidentRoadConditions->fetch(PDO::FETCH_OBJ)) {
$old_rc_array[] = $roadConditions->rc_id;
}
if (isset($_POST['rta_ad_rc'])) {
foreach ($_POST['rta_ad_rc'] as $rc_id) {
if(in_array($rc_id, $old_rc_array)){
unset($old_rc_array[array_search($rc_id, $old_rc_array)]);
}else{
$new_rc_array[] = $rc_id;
}
}
}
foreach ($old_rc_array as $rc_to_delete) {
AccidentRoadConditions::deleteByADIdAndRCId($hidden_acc_det_id, $rc_to_delete);
}
foreach ($new_rc_array as $rc_to_insert) {
AccidentRoadConditions::save(array(null, $hidden_acc_det_id, $rc_to_insert));
}
I think this is what you should do.
Create composite unique constraint on ad_id and rc_id
Delete all the rows not in the selected checkbox ids.
Try to insert all the rows but user INSERT IGNORE. This will insert the record if it does not exist or it will just ignore it. As you are using some framework see how you can do that.
If you can not then just wrap it using try/catch and ignore if the error is related to constraint violation.
This way You don't need to check if the values exist and also there will not be any unnecessary inserts.