My SQL triggers - php

Is it possible to set up a mysql trigger that fires back the id number of that record when ever there is an insert into the database AND how do i capture that using php?

Unless I don't fully understand your question, you don't need a trigger for this - just use the "last inserted ID" functionality of your database driver.
Here's an example using the basic mysql driver in PHP.
<?php
$db = mysql_connect( 'localhost', 'user', 'pass' );
$result = mysql_query( "insert into table (col1, col2) values ('foo', 'bar')", $db );
$lastId = mysql_insert_id();
This is a connection-safe way to obtain the ID.

As explained in the previous answers, you'd don't need to use a trigger to return the identity. You can use the mysql_insert_id() command as described in the [documentation][1].
However if you need to use the new insert id in a trigger, use NEW.[identity_column_name] as follows:
CREATE TABLE temp (
temp_id int auto_increment,
value varchar(10),
PRIMARY_KEY(temp_id)
);
CREATE TRIGGER after_insert_temp AFTER INSERT ON temp
FOR EACH ROW
BEGIN
DECLARE #identity;
SET #identity = NEW.temp_id;
-- do something with #identity
END

I'm not really sure what you're asking. Are you wanting to insert a row into the database and get the id it was assigned too? If so do this
printf("Last inserted record has id %d\n", mysql_insert_id());

You do not need a trigger to accomplish what you are trying to do.
Simply calling PHP's mysql_insert_id will return the ID generated from the last INSERT query executed.
Described here:
http://us2.php.net/manual/en/function.mysql-insert-id.php

Related

How to check for duplicates before inserting into database?

So I made a function to add photos to favorites, how do I make it so I don't keep adding the same images?
My code:
function addToFavorites($fileName)
{
global $conn;
$email = $_SESSION['email'];
$imageId = $_GET["id"];
$sql = "insert into favorites set UserEmail='".mysqli_real_escape_string($conn, $email)."', ImageID=".$imageId;
$result = mysqli_query($conn, $sql);
Any help would be great thanks!
You let the database do the work! Simply define a unique constraint or index on the table:
alter table favorites add constraint unq_favorites_useremail_imageid
unique (useremail, imageid);
With this constraint in place, the database will return an error if you attempt to insert a duplicate.
If you want to avoid the error, you can use on duplicate key update:
insert into favorites (UserEmail, ImageId)
values (?, ?)
on duplicate key update ImageId = values(ImageId);
Some notes about this:
The ? is a parameter placeholder. Learn to use parameters rather than munging values in query strings.
This does not use set. That is a MySQL extension. There is no advantage in this case; you might as well use the standard syntax.
The on duplicate key is a no-operation, but it prevents the code from returning an error when there is a duplicate.
If you want to avoid errors like Gordon Linof said you have execute query:
SELECT FROM favorites WHERE UserEmail='".mysqli_real_escape_string($conn, $email)."' AND ImageID=".$imageId
and if it returns 0 records to execute the insert one. This is the safest way.

get auto increment value for an inserted row safely

i have a table in the database contains _id column which is the primary key for this table , actually this column value is set by the auto increment approach , is there any safe way to get the value that the auto increment value given to the row i when i make the insert ??? i saw a solution says :" call mysql_insert_id() immediately after your insert query." is it safe to use( i.e does it get a wrong value if the same script in different thread )??? if not is there any way to make a synchronized block in php?
as far as I know, the id returned from mysql_insert_id is the auto increment id from the last insert query for the current connection (mysql_connect) to the sql database. The only reason for having to call it right after the query is that if you run two insert queries right after each other, mysql_insert_id returns just the last query. It wouldn't be reliably possible to get the id from the first query. Also, it gets the id from the last query, so if you did an insert then update, then ran mysql_insert_id. It would return 0 because the last query (update) isn't an insert.
Also, php just calls the mysql function mysql_insert_id. From the mysql manual:
The value of mysql_insert_id() is affected only by statements issued
within the current client connection. It is not affected by statements
issued by other clients.
If your different threads are each using their own connection to the MySQL server, it should be fine. If not, you'll probably have to use a mutex or semaphore, which should be provided by your threading library.
Yes; $id = mysql_insert_id(); straight after your query.
It's usualy safe to do it, but there maybe be synchronization problems.
What i suggest is to put your sqls into a transaction block :
mysql_query('BEGIN TRANSACTION');
mysql_query('INSERT...');
$x = mysql_insert_id();
mysql_querry('COMMIT');
EDIT: you also may put a write lock on the table until you read the id and then release the lock. But you only need this if you have synchronization problems (same thread)
In PDO, the correct way is to use PDO::lastInsertId()
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
}catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
As well You can use single one query to get autoincrement id, like:
INSERT INTO table_name(field_1,field_2) VALUES(:field_1,:field_2) RETURNING id;
or
INSERT INTO table_name (field_1) OUTPUT INSERTED.id VALUES (?);
Both are returning your autoincrement id
Regarding to:
https://www.php.net/manual/en/pdo.lastinsertid.php

How to add data off HTML page into MySQL DB

How can I add data from a HTML page, into a MySQL Database based on the attributes?
It's already scraped data, but I would like to import links into a particular field in a table and remove some things from them (ill work that out) and another from into another field in a table.
I have PHP/MySQL and Linux. Should I use curl, and if so how do I actually add data into a MySQL DB?
Some PHP example to Insert and update data:
//***************************************
// Connect to database
//
mysql_connect('127.0.0.1','MyUserName','MyPassword',false,MYSQL_CLIENT_SSL|MYSQL_CLIENT_COMPRESS);
mysql_select_db('MyDatabase');
// If you work with UTF-8 it would be a good idea to set the character set as well to be sure.
//mysql_set_charset('utf8_general_ci');
//***************************************
// Insert new data
//
$MyURL = mysql_real_escape_string("http://www.exampledomain.com/product/");
$Result = mysql_query("INSERT INTO ProductTable (URLField) VALUES ('".$MyURL."')");
if($Result)
print mysql_affected_rows();
//***************************************
// Update existing data
//
$MyURL = mysql_real_escape_string("http://www.exampledomain.com/newproduct/");
$RecordID = 123;
$Result = mysql_query("UPDATE ProductTable SET URLField='".$MyURL."' WHERE ID=".$RecordID);
if($Result)
print mysql_affected_rows();
Connect to the MySQL Server with mysql_connect() and use mysql_select_db() to select the database.
I'm not native English and use UTF-8 to get all the special character correct. If you have no need of this you can ignore this line.
All data that goes into a SQL server should be be sanitized, meaning escaping control characters such as quotes. The Variable $MyURL is sanitized with mysql_real_escape_string() before it is used in the SQL statement.
The SQL statement is executed with mysql_query() and returns true or false (for INSERT and UPDATE statements). With mysql_affected_rows() you can see how many rows that was affected by the SQL statement, a way to see if it worked as expected.
Next comes an UPDATE example to change data in a single column and/or row. The $RecordID variable is the record ID you want to update (you need to know what record you want to update). This example is pinpointing a single record. By changing the WHERE clausule you can update a whole bunch of rows at the same time. For example
UPDATE ProductTable SET URLField='".$MyURL."' WHERE URLField='http://www.exampledomain.com/oldproduct/'
...will update all rows that have 'http://www.exampledomain.com/oldproduct/' in the field URLField.
I think this will get you going for a while...
http://us3.php.net/manual/en/function.mysql-query.php
You will then use a MySQL query like "INSERT INTO table_name (column1,column2) VALUES ('Testing','Testing 2')

MYSQL: SQL query to get the value of autoincrement field

I have a table. The primary key is id and its auto incremented.
Now when I insert a new record, I need to get the id with which the record was updated.
How can I do that? If i use the query...
select max(id) from table_name
...after executing I can get the id. But can I be sure that its the id of the record that was just inserted? Because many people will be using the app at same time.
I am using php and mysql.
Can ayone provie me a sample code snippet in php with mysql?
If you want to find out what the newest ID from an auto increment column is, you just have to run the mysql_insert_id() function right after your insert query.
Like so:
//--connection already made to database
//--now run your INSERT query on the table
mysql_query("INSERT INTO table_name (foo_column) VALUES ('everlong')");
//-- right after that previous query, you run this
$newest_id = mysql_insert_id();
And now $newest_id will contain the ID of the latest row inserted.
Assuming you're using the MySQLi PHP extension, the command you want is mysqli_insert_id
In SQL you can do this
SELECT LAST_INSERT_ID()
In php you can call mysql_insert_id()
Using the same connection, run this query next:
SELECT LAST_INSERT_ID()
Your database driver may have a convenience function for that.
Read the docs.
you can use this to get the value of the next auto_increment value (given that you already connected to the server and selected the db;
$query = "SHOW TABLE STATUS LIKE 'tbl_name'";
$result = mysql_query($query);
$auto_incr_val = mysql_result($result, 0, 'Auto_increment');
echo $auto_incr_val;
This will give you the value that will be used next in the auto_increment column.
EDIT: I'm sorry.. That wasn't your question....
Here is example in PHP:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("YOUR QUERY HERE", $link);
$inserted_id = mysql_insert_id($link));
Query
show create table
contains information you need in last string

php mysql_insert_id(); not working

Hi guys I was hoping from some help here, please.
I have a INSERT query to a table, after this is done I am calling:
mysql_insert_id();
In order to send the last ID inserted into the table to the next page like this:
$insertGoTo = "confirm_booking.php?booking_ID=" .$_POST['booking_ID']. "";
Unfortunately it does not work, all I get is a zero.
The table I am inserting into has an auto increment number and values are inserted into it.
I have also tried SELECT MAX(id) FROM mytable. This dosn't work neither.
I know that this problem has been talked about already. I read all posts but nothing came useful.
Many thanks Francesco
You have to use the value returned by MySql_Insert_Id () when you generate your link:
// your query
$newId = MySql_Insert_Id ();
$insertGoTo = "confirm_booking.php?booking_ID=" . $newId;
It is possible that your table does not have any AUTO_INCREMENT field!
It could also happen because you have two or more mysql connections at the same time.
In this case you should use a link identifier.
$link = mysql_connect( ... );
mysql_select_db('mydb', $link);
mysql_query('INSERT mytable SET abc="123"', $link);
$inserted_id = mysql_insert_id($link);
Some key points from the PHP Manual:
The ID generated for an AUTO_INCREMENT
column by the previous query on
success, 0 if the previous query does
not generate an AUTO_INCREMENT value,
or FALSE if no MySQL connection was
established.
If not having an AUTO_INCREMENT field is not your problem, you might want to try storing the result of the mysql_query call and using that as an argument to the id function
$result = mysql_query("...");
$id = mysql_insert_id($result);
Had an issue using a query like this:
INSERT INTO members (username,password,email) VALUES (...)
reason being that the id (which is my primary key and Auto Increment field) is not part of the query.
Changing it to:
INSERT INTO members (id,username,password,email) VALUES ('',...)
using a an empty value '' will have MySQL use the Auto Increment value but also allow you to use it in your query so you can return the insert id
mysql_insert_id may return 0 or false if your insert fails right?
So if you have trouble with mysql_insert_id not retunring what you expect confirm that you don't have a unique constraint or some other problem with your sql that would cause the insert to fail. Using max is a terrible idea if you consider this.
Make sure to put mysql_insert_id()after the
mysql_query($sql, $con); //Execute the query
Above query responsible for execute your Insert INTO ... command.
After you can get the last ID inserted
I have also suffer from this problem. Finally I found that the problem occur in my connection to the database. You can use this following connection code to connect the database then you can easily use mysqli_insert_id().
$db_connect = mysqli_connect("localhost", "root", "", "social");
Then you can use mysqli_insert_id() as
$id = mysqli_insert_id($db_conx);
I hope this will help you. I you have any problem then leave your comment.
The mysqli_insert_id function has been deprecated. This may be your problem.
Instead, try $mysqli->insert_id. See the documentation for more info.

Categories