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.
Related
I am trying to insert a tuple into PostgreSql using PHP. After inserting the tuple I want to get the value of one of the columns of the inserted row. This column value is generated automatically by the db as it is defined as SERIAL in DDL.
$query = "INSERT INTO posts VALUES('$title','$msg',$x,$y,'$me')";
$result = pg_query($dbh,$query);
if (!$result) {
$status = 0;
} else {
$status = 1;
}
$row = pg_fetch_assoc($result);
$pID = $row['postID'];
$array = array(
'status' => $status,
'pID' => $pID
);
#Delete query is only for checking if the code is working.
$query = "DELETE FROM posts WHERE postID='$pID'";
$result = pg_query($dbh,$query);
The table 'posts' has following DDL:
CREATE TABLE posts
( title CHAR(20),
content CHAR(42),
x_coor INTEGER,
y_coor INTEGER,
userID CHAR(50),
time_stamp TIMESTAMP default current_timestamp,
postID SERIAL,
PRIMARY KEY(postID),
FOREIGN KEY (userID) REFERENCES users ON DELETE CASCADE);
I want to get the value of 'postID' column when I insert a row into the table 'posts' to perform additional functions based on postID. I have tried pg_fetch_assoc, pg_fetch_row, pg_fetch_object & pg_fetch_array. None of those seem to work. (I made appropriate modifications to the code when using each of those functions.)
Is there something incorrect in the code or perhaps I am missing something?
Thanks!
A good way is the returning clause:
INSERT INTO posts
VALUES('$title','$msg',$x,$y,'$me')
RETURNING id;
My PHP is a bit rusty, but it'd look something like:
$query = "INSERT INTO posts VALUES('$title','$msg',$x,$y,'$me') RETURNING id";
$result = pg_query($dbh, $query);
if ($result) {
$row = pg_fetch_row($result);
$inserted_id = $row[0];
}
I have a query that returns the next auto-increment value (id), and I use that value when I'm inserting data in table t_name.
SELECT AUTO_INCREMENT id
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'db_name'
AND TABLE_NAME = 't_name'
But I want that this query gives a different value each time. E.g. Me and my pal are inserting data in db at same time, so I will get one id, he will get another. When I run this query, I want it to give me a different and incremented value each time.
Is it possible? Or do I have to create tables with sequences?
You can insert and than get the last inserted id:
$connection = mysqli_connect($rv, $username, $pass, $mydatabase);
$result = $connection->query('INSERT INTO mytable (id, name) VALUES("", "myName")');
if($result)
{ $lastId = connection->insert_id;
// so something with $lastId...
}
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);
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.
Does it work for anyone? :P
I can properly get insert_id while inserting, but not on update. Of course contactsId column is AUTO_INCREMENT.
Whole code:
<?php
$mysqli = new mysqli('localhost', [USER], [PASSWORD], [DB]);
$mysqli->set_charset("utf8");
$query = 'INSERT INTO contacts (contactsName) VALUES ("Mariola")';
$result = $mysqli->query($query);
echo $mysqli->insert_id . '<br />';
$query = 'UPDATE contacts SET contactsName = "Mariola" WHERE contactsId = 289';
$result = $mysqli->query($query);
echo $mysqli->insert_id;
Output:
1514
0
I HAVE record with id 289, and update works fine.
This behavior is described very clear in the document.
mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated
id used in the last query
If the last query wasn't an INSERT or UPDATE statement or if the
modified table does not have a column with the AUTO_INCREMENT
attribute, this function will return zero.
From MySQL documentation on LAST_INSERT_ID():
If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID(). This can be used to simulate sequences:
Create a table to hold the sequence counter and initialize it:
mysql> CREATE TABLE sequence (id INT NOT NULL);
mysql> INSERT INTO sequence VALUES (0);
Use the table to generate sequence numbers like this:
mysql> UPDATE sequence SET id=LAST_INSERT_ID(id+1);
mysql> SELECT LAST_INSERT_ID();
The UPDATE statement increments the sequence counter and causes the next call to LAST_INSERT_ID() to return the updated value. The SELECT statement retrieves that value. The mysql_insert_id() C API function can also be used to get the value. See Section 20.6.7.37, “mysql_insert_id()”.
Maybe something like this will work:
$query = 'UPDATE contacts SET id = LAST_INSERT_ID(id), contactsName = "Mariola" WHERE contactsId = 289';