inserting a field the a_i value of another field - php

I have a table with the following fields: gallery(picID, picTimeStamp, location).
What I want is that when someone is uploading a new picture to the gallery, the location will get the same value that picID gets (and picID gets its value by auto increment).
I have tried:
"INSERT INTO gallery(picID, picTimeStamp, location) VALUES (null,'.time().',picID)"
but it is not working. I do not get any errors, the location just always has a zero in it.
Thanks!

You should probably be using trigger like this
CREATE TRIGGER trigger_name BEFORE INSERT ON gallery FOR EACH ROW
BEGIN
DECLARE next_id INT;
SET next_id = (SELECT AUTO_INCREMENT FROM gallery WHERE TABLE_NAME='gallery');
SET NEW.location=next_id;
END
edit: Should be after insert trigger instead of before because auto_increment number only gets set after the record is inserted. Sorry bout that!

Your table should be like this:
id | int | primary key/autoincrement
order | int | index
picTimeStamp | timestamp
and then if you want to create a new entry below pass the order number by GET:
function createBelow(){
if(isset($_GET["orders"])){
$orders = $_GET["orders"];
$query = "UPDATE links SET orders=orders+1 WHERE orders>$orders ORDER BY orders DESC";
mysql_query($query);
$query = "INSERT INTO `mydb`.`mytable` (`orders`) VALUES ($orders+1);";
mysql_query($query);
}
}
The default value takes care of id and timestamp, you don't enter these.

Related

Update data in mysql column field without removing previous value

I am trying to update "new" column value with new value but problem is my query remove previous data while inserting new value
What is want: here is example table structure,
Table name = agg_lvl primary key set = uid
uid | new
--------|--------
1 | 100
2 | 300
You can see "new" has 100 points, for example I send 100 new points to user 1, so new column value should be 100 + 100 = 200, right now with this code
$query4 = mysql_query("INSERT INTO agg_lvl (uid, new) VALUES ('$uid','$new')
ON DUPLICATE KEY UPDATE uid='$uid',new='$new'");
Not sure what
new = '$new'
I have tried both ways but no success = >
new = 'new + $new' or new = new + '$new'
You should make changes in your query
Make num = nun+$num to add new value to old one
Remove quotes arount $new because it is a number but not a string
Remove uid from set list because insert already point to that record
And your query should look so:
$query4 = mysql_query("INSERT INTO agg_lvl (uid, new) VALUES ('$uid','$new')
ON DUPLICATE KEY UPDATE new=new+$new");
Okay first i will answer with the proper way to do the same, In this case i am assuming that UID is unique, so you make a new table scorecard with UID as foreign key. Now rather than update, you just insert stuff to table like if UID 1 gains 10 and 20 points, there are two entries. onw with 10 and one with 20. Now to get his current points, you add all points where UID=1 .
Now in your implementation the correct query would be
UPDATE userData SET points = points + x WHERE UID = $uid
where x is the new points gained and points is the name of column
$query4 = mysql_query("INSERT INTO agg_lvl (uid, new) VALUES ('$uid','$new')
ON DUPLICATE KEY UPDATE uid='$uid',new=new+$new");
worked for me with help of #splash58

Get sql Id and insert it into another query instantly

I have two tables first called messages and the other called messages_reply.
I used this code to insert into messages table:
$query = "INSERT INTO `messages` VALUES('', '$id', '$otherId', '')";
$query_run = mysqli_query($connect, $query);
I have the first column auto_increment thats why I left it empty by writing ''
Now i want this auto_increment value that i have inserted to be inserted in the other table called messages_reply
Do I have to create another query to return it or there is an instant way to insert it here and there?
you have to select the last id on table messages first, then you can insert that last id + 1 into messages reply
$query_sel_last_id = "SELECT id FROM messages ORDER BY id desc LIMIT 1"; // select the last id
after that, you only need to insert to messages_reply, remember to plus the value
$query_sel_last_id + 1
EDIT: gordon's solution is better and simpler, LAST_INSERT_ID()

Add a new record to database after checking value

I am inserting data into a database fine with the user entering a reference number eg 1234. Can I change my insert to not require the user to input the value and for the last value entered to be checked and then the reference number being inserted be incremented by one and then inserted with the other data. Bit of a new bee. Here is my current code
$Reference_No = $_POST['Reference_No'];
$Property_Name = $_POST['Property_Name'];
$Property_Area = $_POST['Property_Area'];
mysql_query("INSERT INTO properties (Reference_No, Property_Name, Property_Area)
VALUES ('$Reference_No', '$Property_Name', '$Property_Area')");
You need to make the Reference_No an AUTO_INCREMENT.
Step 1:Create table
CREATE TABLE properties (
Reference_No int AUTO_INCREMENT ,
Property_Name varchar(255),
Property_Area varchar(255),
PRIMARY_KEY (Reference_No)
)
Step 2 : Set the start for auto increment of primary key if you like
ALTER TABLE properties AUTO_INCREMENT=1234;
Step 3: Insert the data into the table
INSERT INTO properties (Property_Name, Property_Area)
VALUES ('$Property_Name', '$Property_Area')");
interogate the database for the Reference NO (where property name matches if you need it)
$reference_no_query = mysql_query("SELECT Reference_No FROM properties WHERE Property_Name = $Property_Name");
pull the Reference No out of the database
$Reference_no = mysql_fetch_array($reference_no_query)
display the Reference no
echo $Reference_no('Reference_no');
you can (and should) tie the data to a variable then echo the var like this:
$Reference_no_display = $Reference_no('Reference_no');
then display it directly from the variable anywere and as many times as you want in the page below the query:
echo $Reference_no_display;
This seems to do the trick for the final bit
printf("Last inserted record has id %d\n", mysql_insert_id());

Adding 2000 autocomplete field records to an existing mysql table

I have a table named users
fields:
ID INT
First_name VARCHAR
Second_name VARCHAR
National_ID INT
The ID field is an AUTO_INCREMENT.
I need to AUTO_INCREMENT the first 2000 users with just the ID and the other fields remain blank,so that the new users will start at 2001.
Kindly assist.
It's called auto increment, your ID column must be set to auto increment.
ALTER TABLE users AUTO_INCREMENT=2001;
Update
If you wish to actually create those rows (not just set the auto increment value) you can use PHP for this:
for($i=1; $i<=2000; $i++)
{
$query = 'INSERT INTO users (id) VALUES ('.$i.')';
//execute this query using your desired PDO or sql extension
}

Add Prefix to auto-increment in mysql db

I have my database with table test1.
It has a primary id "Id" which is auto-increment.
Now the id is in the format 1,2,3.. . .Is it possible to store the primary Id as
PNR1,PNR2,PNR3 .. . . and so on(with auto-increment).
No. Either add the prefix in the query, or use a view instead.
Not really, but you can use another column (but a view)
this is already covered here:
MySQL Auto Increment Custom Values
Yes you can do it if you have INT prefix. You have id as INT in table
// START PREFIX
$query = mysql_query("SELECT id FROM `table_name` ORDER BY id DESC LIMIT 1");
// GET THE LAST ID MAKE SURE IN TABLE YOU 9991
while ($row = mysql_fetch_object($query)) {
$lastId = $row->id;
}
list($prefix,$Id) = explode('999',$lastId );
$Id = ($Id+1);
$new_id = '999'.$Id;
// END PREFIX
$insertQuery = mysql_query("INSERT INTO `table_name` SET id = '".$new_id."',...");
Hi, I made it work in this way :
Products Table (products):
id_prod(varchar(11), NOT NULL, PK), name(varchar(40))
Products Sequence Table (productidseq):
id(AI, PK, NOT NULL)
Before Insert Trigger in Products Table:
CREATE DEFINER=`root`#`localhost` TRIGGER `dbname`.`products_BEFORE_INSERT` BEFORE INSERT ON `products` FOR EACH ROW
BEGIN
insert into productidseq (id) values(NULL);
set new.id_prod = concat('PROD or any prefix here',last_insert_id());
set #productId = new.id_prod; -- To use outside of trigger this variable is useful.
END
When you run below query :
insert into products (name) values('Bat');
data inside tables will we be like this :
products:
id | name
---|-----
1 | Bat
productidseq:
id
---
1
If any better way than this or any cons with this, please comment below. Thanks.

Categories