Yii - get auto increment id - php

I wish to get the auto increment id from my db and call inside my controller.
The 'id' in db is primary key with auto increment.
I tried:
$id = $model->id;
$id = $model->find('id');
$id = $model->findByPK('id');
But the value is blank, any suggestion for me to get the correct id?
Reason why I need the id value is because I need id mix with other value and save into other column.
Thanks.

$newId = YourModel::find()->max('id') + 1;

AUTO_INCREMENT is a special value which may differ from the ID of the last record.
If records deleted, the AUTO_INCREMENT will still continue.
If records failed to insert, the AUTO_INCREMENT will still continue.
Assume you are using MySQL, you can see its value in phpMyAdmin.
Open a database, then a table.
Switch to the Operations tab.
Find the AUTO_INCREMENT field under Table options.
So you should obtain its value, especially when you depend on the AUTO_INCREMENT of your database.
For inserting one record, getting the LAST_INSERT_ID() could be an option. But I still don't prefer to do triple operations (insert, read ID, update). Better to minimize the I/O operations (read AUTO_INCREMENT, insert).
In my case, I need to import data from an Excel document. Surely, when performance is important, I cannot depend on the ActiveRecord model. So I use batchInsert() command.
I am adopting this answer for getting the AUTO_INCREMENT value in MySQL.
$lastModelId = Yii::$app->db->createCommand("
SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'my_table'
")->queryScalar();
If using table prefix:
$lastModelId = Yii::$app->db->createCommand("
SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = :TableName
")->bindValues([
':TableName' => MyModel::getTableSchema()->name,
])->queryScalar();

The easiest way would be to get the new ID after saving the record. After that you can do what you need and save it again. Sth like this:
<?
$model = new YourModel;
$model->field1 = 'some value';
$model->field2 = 'some value 2';
//...
$model->save();
// now you have the new ID and you can use it
$id = $model->id;
// do what you need e.g.
$model->field3 = $field2 + $id;
$model->save();
?>

this worked for me.
public static function getAutoIncrement($table_name)
{
$q = new Query();
$res = $q->select("AUTO_INCREMENT")
->from('INFORMATION_SCHEMA.TABLES')
->where("TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '" . $table_name . "'")
->one();
if($res)
return $res["AUTO_INCREMENT"];
return false;
//or use this
//$q = "SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '" . $table_name . "'";
//$auto_increment = Yii::$app->db->createCommand($q)->queryScalar();
//return $auto_increment;
}

I found my own aswer:
$max = Yii::app()->db->createCommand()->select('max(id) as max')->from('TABLENAME')->queryScalar();
$id = ($max + 1);
print_r($id);
Thanks.

You are going about this the wrong way...
$model->id This is available if you have instantiated the $model prior so:
$model = new Model();
$id = $model->id; //this will work if id is the exact name of the column in db
$model->find('id') This finds elements in DB based on the id... but the syntax in wrong so it would throw an error
$model->findByPK('id') Again... find by pk returns a single row from DB if a match with the primary key (which you should have before making this call)
In conclusion, I would recommend the first way but do not forget to instantiate the model first. Otherwise, you can do something like...
$model = Model::model()->findByAttributes(array('some_attribute' => $attribute_value));
$id = $model->id;
Hope this helps!
Keep on coding!
Ares.

Related

mysql_fetch_assoc returning NULL

I have an issue with the following script which is suppose the next increment value
$lastidquery = "SELECT AUTO_INCREMENT FROM information_schema.tables WHERE TABLE_SCHEMA = DATABASE( ) AND TABLE_NAME = 'user';";
$lastid = mysql_query($lastidquery);
$id = mysql_fetch_assoc($lastid);
$next_increment = $id['Auto_increment'];
The mysql_fetch_assoc returns a null while the mysql_query returns = resource(9, mysql result)
I found the solution thanks to PaulJ.
I was trying to get the next increment value that I need to use as a foreign key in another table when adding a new row.
I actually inserted the data for the parent table, got the last inserted key using $last_id = $connect->insert_id; and then inserted the data in the child table using the obtained id as foreign key.

How to alter a table (add a column) simultaneously when a row is added (column name = row id) in another table?

How to write code in MySQL such that when ever a row with a primary key id is added to a table, a corresponding column is added in another table such that the name of the column is equal to the id of the row just added.
I tried the following but to no use.
sqlQuery("INSERT INTO table1(name) VALUES('$name')");
$id = sqlQuery("SELECT id FROM table1 WHERE id = LAST_INSERT_ID()");
$id = mysqli_fetch_array($id);
$id = $id['id'];
sqlQuery("ALTER TABLE table2 ADD '$id' INT(2) NOT NULL");
sqlQuery - user defined function that return mysqli_query result.
Any help would be great.
Also, I'm a newbie. Sorry if this is a silly question to ask.
Make it OOP style and there is a var in the class that automatically returns the last updated item.
$con = new mysqli(SQL_HOST, SQL_USER, SQL_PASSWORD, SQL_DATABASE); //do normal error checking with database connection
$sql = "INSERT INTO table1(name) VALUES('$name')";
$con->query($sql);
$sql2 = "ALTER TABLE table2 ADD '$con->insert_id' INT(2) NOT NULL" //$con->insert_id is the parm you are looking for.
$con->query($sql2);

Getting the last id from empty mysql table [duplicate]

How to get the next id in mysql to insert it in the table
INSERT INTO payments (date, item, method, payment_code)
VALUES (NOW(), '1 Month', 'paypal', CONCAT("sahf4d2fdd45", id))
You can use
SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'table_name'
AND table_schema = DATABASE( ) ;
or if you do not wish to use information_schema you can use this
SHOW TABLE STATUS LIKE 'table_name'
You can get the next auto-increment value by doing:
SHOW TABLE STATUS FROM tablename LIKE Auto_increment
/*or*/
SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES
WHERE table_name = 'tablename'
Note that you should not use this to alter the table, use an auto_increment column to do that automatically instead.
The problem is that last_insert_id() is retrospective and can thus be guaranteed within the current connection.
This baby is prospective and is therefore not unique per connection and cannot be relied upon.
Only in a single connection database would it work, but single connection databases today have a habit of becoming multiple connection databases tomorrow.
See: SHOW TABLE STATUS
This will return auto increment value for the MySQL database and I didn't check with other databases. Please note that if you are using any other database, the query syntax may be different.
SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'your_table_name'
and table_schema = 'your_database_name';
SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'your_table_name'
and table_schema = database();
The top answer uses PHP MySQL_ for a solution, thought I would share an updated PHP MySQLi_ solution for achieving this. There is no error output in this exmaple!
$db = new mysqli('localhost', 'user', 'pass', 'database');
$sql = "SHOW TABLE STATUS LIKE 'table'";
$result=$db->query($sql);
$row = $result->fetch_assoc();
echo $row['Auto_increment'];
Kicks out the next Auto increment coming up in a table.
In PHP you can try this:
$query = mysql_query("SELECT MAX(id) FROM `your_table_name`");
$results = mysql_fetch_array($query);
$cur_auto_id = $results['MAX(id)'] + 1;
OR
$result = mysql_query("SHOW TABLE STATUS WHERE `Name` = 'your_table_name'");
$data = mysql_fetch_assoc($result);
$next_increment = $data['Auto_increment'];
Use LAST_INSERT_ID() from your SQL query.
Or
You can also use mysql_insert_id() to get it using PHP.
Solution:
CREATE TRIGGER `IdTrigger` BEFORE INSERT ON `payments`
FOR EACH ROW
BEGIN
SELECT AUTO_INCREMENT Into #xId
FROM information_schema.tables
WHERE
Table_SCHEMA ="DataBaseName" AND
table_name = "payments";
SET NEW.`payment_code` = CONCAT("sahf4d2fdd45",#xId);
END;
"DataBaseName" is the name of our Data Base
Simple query would do
SHOW TABLE STATUS LIKE 'table_name'
For MySQL 8 use SHOW CREATE TABLE to retrieve the next autoincrement insert id:
SHOW CREATE TABLE mysql.time_zone
Result:
CREATE TABLE `time_zone` (
`Time_zone_id` int unsigned NOT NULL AUTO_INCREMENT,
`Use_leap_seconds` enum('Y','N') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'N',
PRIMARY KEY (`Time_zone_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1784 DEFAULT CHARSET=utf8 STATS_PERSISTENT=0 ROW_FORMAT=DYNAMIC COMMENT='Time zones'
See the AUTO_INCREMENT=1784 at the last line of returned query.
Compare with the last value inserted:
select max(Time_zone_id) from mysql.time_zone
Result:
+-------------------+
| max(Time_zone_id) |
+-------------------+
| 1783 |
+-------------------+
Tested on MySQL v8.0.20.
SELECT id FROM `table` ORDER BY id DESC LIMIT 1
Although I doubt in its productiveness but it's 100% reliable
You have to connect to MySQL and select a database before you can do this
$table_name = "myTable";
$query = mysql_query("SHOW TABLE STATUS WHERE name='$table_name'");
$row = mysql_fetch_array($query);
$next_inc_value = $row["AUTO_INCREMENT"];
I suggest to rethink what you are doing. I never experienced one single use case where that special knowledge is required. The next id is a very special implementation detail and I wouldn't count on getting it is ACID safe.
Make one simple transaction which updates your inserted row with the last id:
BEGIN;
INSERT INTO payments (date, item, method)
VALUES (NOW(), '1 Month', 'paypal');
UPDATE payments SET payment_code = CONCAT("sahf4d2fdd45", LAST_INSERT_ID())
WHERE id = LAST_INSERT_ID();
COMMIT;
You can't use the ID while inserting, neither do you need it. MySQL does not even know the ID when you are inserting that record. You could just save "sahf4d2fdd45" in the payment_code table and use id and payment_code later on.
If you really need your payment_code to have the ID in it then UPDATE the row after the insert to add the ID.
What do you need the next incremental ID for?
MySQL only allows one auto-increment field per table and it must also be the primary key to guarantee uniqueness.
Note that when you get the next insert ID it may not be available when you use it since the value you have is only within the scope of that transaction. Therefore depending on the load on your database, that value may be already used by the time the next request comes in.
I would suggest that you review your design to ensure that you do not need to know which auto-increment value to assign next
use "mysql_insert_id()". mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value.
Below are the example of use:
<?php
$link = mysql_connect('localhost', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable VALUES('','value')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
I hope above example is useful.
If return no correct AUTO_INCREMENT, try it:
ANALYZE TABLE `my_table`;
SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE (TABLE_NAME = 'my_table');
This clear cache for table, in BD
using the answer of ravi404:
CREATE FUNCTION `getAutoincrementalNextVal`(`TableName` VARCHAR(50))
RETURNS BIGINT
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE Value BIGINT;
SELECT
AUTO_INCREMENT INTO Value
FROM
information_schema.tables
WHERE
table_name = TableName AND
table_schema = DATABASE();
RETURN Value;
END
using in your insert query, to create a SHA1 Hash. ex.:
INSERT INTO
document (Code, Title, Body)
VALUES (
sha1( getAutoincrementalNextval ('document') ),
'Title',
'Body'
);
Improvement of #ravi404, in case your autoincrement offset IS NOT 1 :
SELECT (`auto_increment`-1) + IFNULL(##auto_increment_offset,1)
FROM INFORMATION_SCHEMA.TABLES
WHERE table_name = your_table_name
AND table_schema = DATABASE( );
(auto_increment-1) : db engine seems to alwaus consider an offset of 1. So you need to ditch this assumption, then add the optional value of ##auto_increment_offset, or default to 1 : IFNULL(##auto_increment_offset,1)
For me it works, and looks simple:
$auto_inc_db = mysql_query("SELECT * FROM my_table_name ORDER BY id ASC ");
while($auto_inc_result = mysql_fetch_array($auto_inc_db))
{
$last_id = $auto_inc_result['id'];
}
$next_id = ($last_id+1);
echo $next_id;//this is the new id, if auto increment is on
SELECT AUTO_INCREMENT AS next_id FROM information_schema.tables WHERE table_name = 'table name' AND table_schema = 'database name of table name'
mysql_insert_id();
That's it :)

how to auto increment variable

I need some quick help, I need to know if I can somehow increment the $user_id by one so that I do not get a duplicate entry error. Do I just add a +1 after ['user_id']?
public function insert_video($video_id,$user_id,$caption) {
$userObject = array();
$userObject['user_id'] = $user_id;
$userObject['video_id'] = $video_id;
$userObject['caption'] = str_replace(array("'",'"'), '', $caption);
$userObject['description'] = '';
$userObject['votes'] = 0;
$userObject['upload_time'] = date('Y-m-d H:i:s');
$userObject['version'] = $this->contests->contest->version; //4
//if($this->contests->contest->auto_approve)
$userObject['approved'] = 1;
$this->db->insert('photos', $userObject);
return $this->db->insert_id();
ok guys I edited the function and removed any mention of user_id but for some reason I still get the error when I try to submit another video. Should I try dropping that column on the table? here is my updated function
public function insert_video($video_id,$caption) {
$userObject = array();
//$userObject['user_id'] = $user_id+1;
$userObject['video_id'] = $video_id;
$userObject['caption'] = str_replace(array("'",'"'), '', $caption);
$userObject['description'] = '';
$userObject['votes'] = 0;
$userObject['upload_time'] = date('Y-m-d H:i:s');
$userObject['version'] = $this->contests->contest->version; //4
//if($this->contests->contest->auto_approve)
$userObject['approved'] = 1;
$this->db->insert('photos', $userObject);
return $this->db->insert_id();
}
You need to set up your user_id To auto increment. If you find it easier as you clearly have a table already set up, use phpMyAdmin to set the AI tick box to true.
Then when you INSERT, you'll get a unique value. You do not need to specify the user_id as that'll be taken care of.
INSERT INTO users (FirstName,LastName) VALUES ('Matt','HB')
I suppose you need to have 2 tables, one that holds a user info with auto incresment column e.g. "ID".
In table photos don't use auto incresment for user_id, as you need to give users ability to insert multiple photos and update current. just change in your table:
`user_id` to `ID` -> this will auto incresment
create new column `user_id` int 200.. this will be a reference of `column - "ID"` from **userinfo** table;
//then run your query:
INSERT INTO photos (user_id, video_id, caption, description, votes, upload_time, version, approved) VALUES (7339, 'fDTm1IzQf-U', 'new test', '', 0, '2014-11-12 16:17:36', '19', 1)

SQL query to alter table column names

I am running this SQL Query in PHP:
$sql="alter table callplandata change '".$_POST["col_name$y"]."' '".$_POST["col_newname$y"]."' ";
to alter column names but before it updates i want to check if the column name already exists and if it does to add a number on the end otherwise to just carry on updating
how can i do this using PHP?
Please, please, please, don't do this. This is about as unsafe a thing to do. However, I will say this: The ALTER TABLE syntax is worth a look:
ALTER TABLE <table name>
CHANGE [COLUMN] old_col_name new_col_name column_definition
Note that the column_definition bit is not optional.
Also, if you want to see if the fieldname given already exists:
SHOW COLUMNS FROM <table_name> /* or SHOW COLUMNS IN tbl */
Then, in PHP, depending on the extension you used, you do something like this:
$existingFields = array();
foreach ($resultSet as $row)
{
$existingFields[] = $row['Field'];
}
SHOW COLUMNS will also give you information concerning the type of each field, if it's a key, or even if it's an auto_increment value details, as ever, on the mysql website
So putting it all together:
$db = new PDO();//connect
$stmt = $db->prepare('SHOW COLUMNS IN callplandata WHERE Field = :field');
$bind = array(
':field' => $_POST['colname_new']
);
$stmt->execute($bind);
if ($row = $stmt->fetch())
throw new InvalidArgumentException($_POST['colname_new'].' already exists!');
$bind[':field'] = $_POST['colname_old'];
$stmt->closeCursor();//reset cursor, so we can re-use the statement
$stmt->execute($bind);//re-use statement
if (!($row = $stmt->fetch(PDO::FETCH_OBJ))
throw new InvalidArgumentException($_POST['colname_old'].' does not exist, cannot rename it!');
//very basic column definition construction here, needs more work, though!
$current = '';
$current = $row->Type. ' '.($row->Null == 'NO' ? 'NOT NULL ' : '').
($row->Default !== '' ? 'DEFAULT '.$row->Default.' ' : '').$row->Extra;
/**
* ADD CODE HERE TO SANITIZE THE NEW COLUMN NAME
* if you want to procede with this madness... I would urge you not to, though!
*/
$pdo->exec(
'ALTER TABLE callplandata
CHANGE '.$_POST['colname_old'].' '.$_POST['colname_new'].' './/rename
$current//add column definition
);
Disclaimer:
The code I posted here is meant to be purely academic. It should not be used, it's unsafe and incomplete. Please rethink what you are trying to do. Avoid, at all cost, using user data to alter how the server stores/structures the data!
Try this
SELECT *
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'db_name'
AND TABLE_NAME = 'table_name'
AND COLUMN_NAME = 'column_name'
In PHP
$result = mysqli_query("SHOW COLUMNS FROM `table` LIKE 'fieldname'");
$exists = (mysqli_num_rows($result))?TRUE:FALSE;
I think you need to specify datatype and default value also.
example
ALTER TABLE `ca_4_4_14` CHANGE `active` `is_active` ENUM('Y','N') CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT 'Y' NOT NULL;

Categories