Codeigniter Active Record Insert Function - php

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;

Related

how to get ID without inserting any data into DB

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.");
}

Update query insert zero in table in ci

Update query insert zero in table everytime.
I have prtinted the query.From phpmyadmin the lastquery working fine.updated with same value
But when db active query then it has updating 0.
tbl_setitbl
set_id(primary key)
reference(text)`
Here is my code.
public function edit_set($id,$setvalue)
{
$data = array('reference' => $setvalue);
$this->db->where('set_id', $id);
$this->db->update('tbl_setitbl', $data);
if($this->db->affected_rows())
return true;
else
return false;
}
I have tried this code also.
$this->db->where('set_id', $id);
$this->db->update('tbl_setitbl', array('reference' => $setvalue));
echo $this->db->last_query();
UPDATE tbl_setitbl SET reference = 'hhhhhhhh' WHERE set_id = 1
Sorry every one...
Get solved
actually the problem is in controller.
query has run two times as redirection has not doing properly
see the result by using $this->db->last_query() then verify the sql code if it is similiar to the sql code that you have tried in phpmyadmin

mysql_affected_rows() returns 0 for UPDATE statement even when an update actually happens

I am trying to get the number of rows affected in a simple mysql update query. However, when I run this code below, PHP's mysql_affected_rows() always equals 0. No matter if foo=1 already (in which case the function should correctly return 0, since no rows were changed), or if foo currently equals some other integer (in which case the function should return 1).
$updateQuery = "UPDATE myTable SET foo=1 WHERE bar=2";
mysql_query($updateQuery);
if (mysql_affected_rows() > 0) {
echo "affected!";
}
else {
echo "not affected"; // always prints not affected
}
The UPDATE statement itself works. The INT gets changed in my database. I have also double-checked that the database connection isn't being closed beforehand or anything funky. Keep in mind, mysql_affected_rows doesn't necessarily require you to pass a connection link identifier, though I've tried that too.
Details on the function: mysql_affected_rows
Any ideas?
Newer versions of MySQL are clever enough to see if modification is done or not. Lets say you fired up an UPDATE Statement:
UPDATE tb_Employee_Stats SET lazy = 1 WHERE ep_id = 1234
Lets say if the Column's Value is already 1; then no update process occurs thus mysql_affected_rows() will return 0; else if Column lazy had some other value rather than 1, then 1 is returned. There is no other possibilities except for human errors.
The following notes will be helpful for you,
mysql_affected_rows() returns
+0: a row wasn't updated or inserted (likely because the row already existed,
but no field values were actually changed during the UPDATE).
+1: a row was inserted
+2: a row was updated
-1: in case of error.
mysqli affected rows developer notes
Have you tried using the MySQL function ROW_COUNT directly?
mysql_query('UPDATE myTable SET foo = 1 WHERE bar = 2');
if(mysql_result(mysql_query('SELECT ROW_COUNT()'), 0, 0)) {
print "updated";
}
else {
print "no updates made";
}
More information on the use of ROW_COUNT and the other MySQL information functions is at: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_row-count
mysqli_affected_rows requires you to pass the reference to your database connection as the only parameter, instead of the reference to your mysqli query. eg.
$dbref=mysqli_connect("dbserver","dbusername","dbpassword","dbname");
$updateQuery = mysqli_query($dbref,"UPDATE myTable SET foo=1 WHERE bar=2");
echo mysqli_affected_rows($dbref);
NOT
echo mysqli_affected_rows($updateQuery);
Try connecting like this:
$connection = mysql_connect(...,...,...);
and then call like this
if(mysql_affected_rows($connection) > 0)
echo "affected";
} else { ...
I think you need to try something else in update then foo=1. Put something totaly different then you wil see is it updating or not without if loop. then if it does, your if loop should work.
You work this?
$timestamp=mktime();
$updateQuery = "UPDATE myTable SET foo=1, timestamp={$timestamp} WHERE bar=2";
mysql_query($updateQuery);
$updateQuery = "SELECT COUNT(*) FROM myTable WHERE timestamp={$timestamp}";
$res=mysql_query($updateQuery);
$row=mysql_fetch_row($res);
if ($row[0]>0) {
echo "affected!";
}
else {
echo "not affected";
}
This is because mySql is checking whether the field made any change or not,
To over come this, I created a new TINY field 'DIDUPDATE' in the table.
added this to your query 'DIDUPDATE=DIDUPDATE*-1'
it looks like.
$updateQuery = "UPDATE myTable SET foo=1, DIDUPDATE=DIDUPDATE*-1 WHERE bar=2";
mysql_query($updateQuery);
if (mysql_affected_rows() > 0)
{
echo "affected!";
}
else
{
echo "not affected";
}
it works fine!!!
Was My Tought !
I was just about to tell to check if the function's being called many times !
Just a little advice:
try using isset() & POST / GET or something like that;
if ( isset( $_POST['Update'] == 'yes' ) ) :
// your code goes here ...
endif;
Hope it was clear and useful, Ciao :)

How do I tell when a MySQL UPDATE was successful versus actually updated data?

How do I tell when a MySQL UPDATE was successful versus actually updated data?
Example:
TABLE
id city_name
1 Union
2 Marthasville
If I run the following:
$data = array('city_name', 'Marthasville');
//update record 2 from Marthasville to the same thing, Marthasville.
$this->db->where('id', 2);
$this->db->update('table', $data);
if($this->db->affected_rows() > 0)
{
//I need it to return TRUE when the MySQL was successful even if nothing was actually updated.
return TRUE;
}else{
return FALSE;
}
This will return TRUE every time the UPDATE statement is successful, but FALSE when no rows were actually updated.
I need it to return TRUE every time the UPDATE statement was successfully executed even if it doesn't actually change any records.
Have a look at mysql_affected_rows()
It should tell you if anything was actually updated as opposed to nothing was successfully updated resulting in a return of true.
php.net says:
mysql_affected_rows()
Returns the number of affected rows on success, and -1 if the last
query failed.
You could use the following to achieve your desired results:
if($this->db->affected_rows() >= 0){ }
Then you would use mysql_query:
SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query()
returns TRUE on success or FALSE on error.
Simple like this:
$result = $this->db->update('table', $data);
if($result)
{
//without error even no row updated
} else {
}

How can I check data has been inserted successfully?

I have two insert statements. The second one will be executed only after successful execution of first one. What I would like to do is:
$sqlone="Insert into .....";
$sqltwo="Insert into.....";
If (mysql_query($sqlone))
{
If (mysql_query($sqltwo))
{
Show message Data inserted in both tables.
}
}
Try this
$query1 = '...';
$query2 = '...';
$query3 = '...';
if(mysql_query($query1)) {
if(mysql_query($query2)) {
if(mysql_query($query3)) {
echo "success";
}
else { echo "error"; }
}
else { echo "error"; }
}
else { echo "error"; }
Sounds like you're looking for transactions.
A bit of googling gave me some info on database transactions in PHP - hope it helps.
That syntax looks like it works, as...
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
http://au2.php.net/mysql_query
From the documentation:
For other type of SQL statements,
INSERT, UPDATE, DELETE, DROP, etc,
mysql_query() returns TRUE on success
or FALSE on error.
So as far as I can see there is no problem with what you already have.
You can also create the DB transaction as well in which commit of one insert will execute the second insert statement..

Categories