How to increment a MySQL database row value - php

I have a MySQL database with a table called chapters.
I have a column called chapter_number which is an Integer data type and is NOT auto increment as I have another field which uniquely identifies the row.
Upon insertion to this table I would like the value of the chapter_number column to be the previous row's chapter_number incremented by 1 (+1).
The purpose of this is to ensure that every time a chapter is added, the right ordering takes place.
How could I achieve this in PHP?
Here is an example of what I mean?
Table structure:
$stmt = $db->prepare('INSERT INTO chapters VALUES (?,?,?,?)');
$stmt->execute(array('','title', '2015-04-03', 'chapter 1 body'));
What would I put for the first parameter ^

SELECT max(chapter_number) + 1 as total FROM table;
This would also allow you to later on have chapters assigned to multiple books by symply adding a where clause
The following example is how this syntax would look
insert into table_one (greeting_column, name_column)
SELECT
'hello',
(SELECT max(chapter_number) + 1 as total FROM table)

Related

How to create duplicate values in database using id in php

Here i already have a row which contains the values, i have a id as a primary key
now what i want to do is using that id i want to duplicate the same row values and create another row.except i want to update 2 column values. how can i do this?
for ex:
in one row i already have the values say
product_id,product_price,product_nos,product_remaining,product_name
now i want to duplicate the above row with changing only one column value
,say product_remaining set value to 10.
How can i do this in php or with query?
You can use the following query if you not use auto_incrementing ids, 10 is the new value for product_remaining.
INSERT INTO table (product_price,product_nos,product_remaining,product_name)
SELECT product_price,product_nos,10,product_name FROM table
WHERE product_id = 1
or this one where you set your id, where 999 is the new id:
INSERT INTO table (product_id,product_price,product_nos,product_remaining,product_name)
SELECT 999,product_price,product_nos,10,product_name FROM table
WHERE product_id = 1

Find highest value in column insert a new record 1 number higher in said column

I am trying to write a single MySQL insert query that will identify the highest value in a column and then increment it by one for the record being inserted. I thought when I made the table that I had this field set to auto_increment but it does not work for some reason. My current insert statement is:
INSERT INTO victoria (name, album, order_by) VALUES (:name, :album, :order)
The order_by field is the one that needs to increment by one.
If you want, for some reason, to increment a value of a column without using an auto_increment column you can do something like this
INSERT INTO victoria
SELECT :name, :album,
COALESCE((SELECT MAX(order_by) FROM victoria), 0) + 1;
Note: it might fail to provide you with a distinct value under heavy load, meaning several concurrent users inserting rows at the same time can grab the same MAX(order_by) value. Therefore if you are not planning to "reorder" rows latter you better stick with an auto_increment column.
Here is SQLFiddle demo

Mysql query Sum with Case

I have two tables.
One contains default data for 3 columns, (value is 1 or 0) In the same table is a ClientID
Another table contains edited data with a date, ClientID and a extra column named 'Changed'
If Changed = 1 then the values in the 3 columns are changed and therefore need to be read from the second table.
This al works fine, but I want to make a report in php where a daterange can be selected and a query should group by ClientID and count all 1's in the selected daterange of the 3 columns. (Each column seperate)
Here's the trick: When Changed = 0 in the specific row then It should check the default value and if Changed = 1 it should check the second table. And then count it with the previous rows.
I hope you understand what I want to create
You can use IF function from SQL
For example
SELECT SUM(IF(Changed=1, t1.col1, t2.col2)) FROM t1, t2 WHERE t1.id=t2.id
This is example how you can use columns for case in SUM

SQL query using replace a value in one table by randomly selecting a value in another table

I have a table with an value that I would like to be updated periodically with a cron job. However, I need to update the value by replacing it with a value from a different table. The issue is that I would like the replacement value to be chosen randomly.
For example, Table 1 has
ID Email
=================
1 bobatumail
Table 2 has:
ID Email
================
1 bobatumail
2 joeatumail
3 peteatumail
4 biffatumail
5 wilneratumail
6 wilsonatumail
I would like the query to replace bobatumail in Table 1 with any of the other values in Table 2 as long as it is random. It could even be the same value as in Table 1.
Any idea how to do this?
In MySQL you could use the REPLACE statement:
REPLACE INTO table1 (ID, Email)
SELECT 1, table2.Email FROM table2 ORDER BY RAND() LIMIT 1;
The "1" in the second line represents the id of the entry while the second part returns a random value out of table2. Yes, there are solutions using the UPDATE statement (JOIN and ANSI) but its always tricky and you usually have to turn off safe update mode.
http://dev.mysql.com/doc/refman/5.5/en/mysql-command-options.html#option_mysql_safe-updates
Please note that REPLACE first deletes the old entry and then reinserts the new one.
http://dev.mysql.com/doc/refman/5.5/en/replace.html

reference auto-increment columns?

I have 2 tables that I am working with that use the same column; one table contains the text and the other table contains the images; they use the column listing_id so that the right text shows up with the right images;
my problem is that because column listing_id is auto-increment, my first table is able to have an insert into query that is able to insert the text and then +1 the column listing_id; however the 2nd table I use another INSERT INTO query will not have the right listing_id,
because some entries for listing_id have been deleted, meaning that the 2nd table's listing_id will always be behind the 1st tables listing_id;
how do I reference the column listing_id?
You need to create an INT column called something like "parent_id" in the dependant tables that stores the id of the main table that it is referencing. When you select records from the first, you would then JOIN the tables with the auto_increment field of the first field against the "parent_id" of the second.
As MrSlayer mentions, use the newly inserted ID of the first table to update "parent_id". You should typically have a unique ID field in the second table for uniqueness, but it shouldn't be part of the relationship to the first table.
If you're unclear about how to get the id that the first table auto_increments to when you insert, use mysql_insert_id().
mysql_query("INSERT INTO table1 ...");
echo "Last inserted record_id in table1 was " . mysql_insert_id();
INSERT INTO table1 (mytextcolumn) VALUES('text');
INSERT INTO table2 (parent_id,image_name) VALUES(LAST_INSERT_ID(),'someimage.png');

Categories