MySQL generate url using already assigned ID - php

I'm trying to generate URL in SQL database using already assigned auto_incremented ID
When a new form is submitted then SQL automatically generates and unique lens_id for me. How can I automatically add it there in this lens_url? (Picture below)

You can do this by creating a trigger on your table. Trigger is as follows,
DELIMITER $$
CREATE TRIGGER `UpdateLensURL` BEFORE INSERT ON `your_table_name`
FOR EACH ROW BEGIN
SET NEW.lens_url= CONCAT('localhost:8888/lensview/post.php?id=', (
SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'your_table_name'
));
END;
$$
DELIMITER ;

There are two options here:
1) Use a stored procedure (which will require code changes for anywhere that inserts rows)
2) Use a trigger and insert as normal - something like below should do the trick:
DELIMITER //
CREATE TRIGGER my_awesome_trigger
BEFORE INSERT
ON your_table_name
FOR EACH ROW
BEGIN
DECLARE next_id int default 0;
SELECT auto_increment INTO next_id
FROM information_schema.tables
WHERE table_name = 'your_table_name'
AND table_schema = DATABASE();
SET NEW.lens_url = CONCAT('localhost:8888/.../', next_id);
END; //
DELIMITER ;

Try something like this
$qry1="insert into tablename(lens_name,lens_url,lens_category,lens_author,lens_discription,lens_repert)values('A','B','C','D','E','F')";// your query to insert data to table
mysqli_query($con,$qry1); // run query
$last_insertid=mysqli_insert_id($con); // save last insetred ID
$url="localhost:8888/lenseview/post.php?id=".$last_insertid; //prepare url
$qry2="upadte tablename set lens_url=$url where lens_id=$last_insertid"; //update query
mysqli_query($con,$qry2); // run your query to update url

I think easiest option would be this
$Last_Lens_IdQ = mysqli_query($conn, "SELECT `lens_id` FROM `table` ORDER BY `lens_id` DESC LIMIT 1");
$Last_LensId = mysqli_fetch_array($Last_Lens_IdQ);
$x = $Last_Lens[0]++;
$LensUrl = "localhost:8888/lenseview/post.php?id=".$x;
Then insert the field and use $LensUrl When inserting the lens url column

Related

How to concat in MySql Insert Before Trigger with Select Statement of Auto Increment ID

I have four columns in a table (Names: prdRevise, prdCode, prdMfgNmbr, prdID). I am inserting values in first two columns through PHP and want to generate prdID with other three. prdMfgNmbr is autoincrement which is currently inserting '0' on new.prdMfgNmbr's place. Below is the trigger I am using.
set new.prdId = concat(new.prdCode, new.prdRevise, new.prdMfgNmbr)
following Query is giving me upcoming Auto_Increment Value. . dont know how to use it in triger.
SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'labautomation'
AND TABLE_NAME = 'prdmfg';
I figured out a way to do the thing at front end in PHP:
$qry5="SELECT `AUTO_INCREMENT`FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'labautomation'AND TABLE_NAME ='prdmfg'";
$qrprId=mysql_query($qry5);
$qrMfgNmbr = mysql_fetch_assoc($qrprId);
$newqrMfgNmbr=$qrMfgNmbr['AUTO_INCREMENT'];
after getting the value I used it with other values from farm to send it into DB in prdID column. But Store procedure thing will still be appreciated.

Use inserted id for another column value

I have an identity column (id) that auto-increments.
id|name|image_path
I want to know if there is some way using mysql, to use the newly inserted id in the image_path.
For example if a new row is inserted and got the id 2 I want the image_path to be "/images/2.png".
Or do I have to use the traditional way, by inserting and then fetching this ID then updating the entry?
My opinion is that it is impossible to do with one query. You won't know new autoincrement value until row will be inserted. Still you can write 1 query to achieve what you want (actually 2 queries would be executed):
insert into `t`(`id`, `name`, `image_path`)
values(
(SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES
WHERE `table_name` = 't'),
'1234',
concat(
'/images/',
(SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES
WHERE `table_name` = 't'),
'.png'
)
)
Anyway much safer would be:
START TRANSACTION;
set #c = (select ifnull(max(`id`),0) + 1 from `t`);
insert into `t`(`id`, `name`, `image_path`) values (#c,'123',concat('/images/',#c,'.png'));
COMMIT;
Yes, it is possible with oracle. We have dynamic sql feature.
have tried the below.
Created a sequence and then created a procedure which takes id as input and creates an insert statement dynamically which will fulfill your requirement.
create sequence seq1 start with 1;
create table image1(id1 number,image varchar2(50));
create or replace procedure image1_insert(id1 in number)
as
sql_stmt varchar2(50);
image_path varchar2(50);
begin
sql_stmt:='insert into image1 values(:1,:2)';
image_path:='/image/'||id1||'.png';
execute immediate sql_stmt using id1,image_path;
end;
begin
image1_insert(seq1.nextval);
end;
id image
4 /image/4.png
5 /image/5.png
select *from image1;

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 update multiple columns from a trigger MySQL

hi i am using mysql trigger to update a table on another table's insertion
this trigger works fine
CREATE TRIGGER `update_pupil_subject` AFTER INSERT ON `pupil_marks`
FOR EACH ROW
BEGIN
UPDATE pupil_subjects SET NumberOfStudens = NumberOfStudens + 1 WHERE NEW.SubjectID = SubjectID;
END$$
but this gives an error
CREATE TRIGGER `update_pupil_subject` AFTER INSERT ON `pupil_marks`
FOR EACH ROW
BEGIN
UPDATE pupil_subjects SET NumberOfStudens = NumberOfStudens + 1 , AverageMarks = (SELECT AVG(Marks) FROM pupil_marks WHERE NEW.StudentID = StudentID ) WHERE NEW.SubjectID = SubjectID;
END$$
how to write this correctly , please help . thanks in advance .
Apparently there were problems when sub-queries were used:
Can you try splitting the SQL statement:
DELIMITER $$
CREATE TRIGGER `update_pupil_subject`
AFTER INSERT
ON `pupil_marks`
FOR EACH ROW
BEGIN
DECLARE avg_marks float;
SELECT AVG(Marks)
INTO avg_marks
FROM pupil_marks
WHERE NEW.SubjectID = SubjectID;
UPDATE pupil_subjects
SET NumberOfStudens = NumberOfStudens + 1, AverageMarks = avg_marks
WHERE NEW.SubjectID = SubjectID;
END
$$
Edit: Use
SHOW TRIGGERS WHERE `table` = 'pupil_marks';
to get all triggers defined on pupil_marks. You can't have multiple triggers on an event as all actions can be covered in single trigger.
NOTE: I think AVG(Marks) is for a given subject, so modified trigger definition accordingly.
declare a variable inside the trigger and assign it with the subquery
declare avg_mark integer default 0;
set avg_mark := (SELECT AVG(Marks) FROM pupil_marks WHERE NEW.StudentID = StudentID);
then use the variable "avg_mark" in your update statement...
it may work...
if not then check the delimiter just below phpmyadmin sql box . It should be "$$"

Get Updated Value in MySQL instead of affected rows

I've been trying to find an answer to this question, but haven't found any definitive "yes" or "no" in all my research.
I'm running a simple MySQL query like this:
UPDATE item SET `score`=`score`+1 WHERE `id`=1
Is there a way for that query to return the updated value, instead of the number of rows affected? Just as a reference, I'm doing this in PHP, so the actual code looks like:
$sql = "UPDATE item SET `score`=`score`+1 WHERE `id`=1";
$new_value = mysql_query($sql);
//Unfortunately this does not return the new value
I know I could do a second query and just SELECT the value, but I'm trying to cut down on queries as much as possible. Is there a way?
You can do it with a stored procedure that updates, and then selects the new value into an output parameter.
The following returns one column new_score with the new value.
DELIMITER $$ -- Change DELIMITER in order to use ; withn the procedure
CREATE PROCEDURE increment_score
(
IN id_in INT
)
BEGIN
UPDATE item SET score = score + 1 WHERE id = id_in;
SELECT score AS new_score FROM item WHERE id = id_in;
END
$$ -- Finish CREATE PROCEDURE statement
DELIMITER ; -- Reset DELIMITER to standard ;
In PHP:
$result = mysql_query("CALL increment_score($id)");
$row = mysql_fetch_array($result);
echo $row['new_score'];
No, there's nothing like postgresql's UPDATE ... RETURNING output_expression in MySQL (yet?).
If you don't want to run another Query SELECT then here is another way to do it. I have modified Mr. Berkowski code for reference:
DELIMITER $$
CREATE PROCEDURE increment_score
(
IN id_in INT
)
BEGIN
set #newScore := null;
UPDATE item SET score = IF((#newScore := score+1) <> NULL IS NULL, #newScore, NULL) WHERE id = id_in;
SELECT #newScore;
END
DELIMITER ;
No you cant. You could make a function or stored procedure that could do the insert and return the updated value but that would still require you to execute two queries from within the function or stored procedure.
You can create a trigger, and you will know everything about the modifications.

Categories