Increment remaining row values in a column based on changing one value - php

I am trying to create a round robin scenario when new leads come in.
When a lead comes in, the following table named "round_robin" will find the position '1' and send the lead data there
Name Type Attributes Null Default Extra
id int(11) No None AUTO_INCREMENT
on_off text Yes NULL
cname text Yes NULL
position int(11) Yes NULL
email varchar(100) Yes NULL
I have some knowledge of PHP so if some coding I used is way off, thats likely why.
This is the code I've started on.
$round_robin_companies = "SELECT * FROM round_robin";
$position_one = "SELECT position FROM round_robin WHERE postion = '1' ";
$query = "SELECT * FROM round_robin WHERE position = '$position'";
$result = mysql_query($query);
if ($result === 1) exit();
else {
UPDATE $position_one SET position='$row_count';
while ($query <= $row_count) {
$row_count++;
}
}
Basically, when a new row is added in a table called leads, I need Company One position to change to $row_count (3) and all the remaining positions to increment down one.
So Company Two position would be 1 and be next in the queue and Company Three would become 2. I want to use row count because I will be adding more companies in the future.
id on_off cname position email
1 on Company One 1 C1#email.com
2 on Company Two 2 C2#email.com
3 on Company Three 3 C3#email.com

Related

how do I retrieve data which has value 1 as the column name and ignore the data which has value of 0 in php

I'm working on a new project using php and mysql
after inserting the values I want to retrieve them as the column name
I'm using this table
CREATE TABLE categories (
ID INT(8) NOT NULL AUTO INCREMENT
,action INT(1) DEFAULT '0'
,comedy INT(1) DEFAULT '0'
,drama INT(1) DEFAULT '0'
,mystery INT(1) DEFAULT '0'
)
values are either 0 or 1 , I want to retrieve the value 1 as the column name like if action and mystery has value = 1 I want to display them alone
what I'm having a hard time is displaying them as the name and only show value 1
edit as requested some sample data
when I try to get the values they appear 0 or 1
$result = mysqli_query($link,"SELECT * FROM categories WHERE ID = $id");
while ($row = mysqli_fetch_assoc($result)) {
echo '
<div class="categories">
'.$row["action"].' -
'.$row["comedy"].' -
'.$row["drama"].' -
'.$row["mystery"].' </div>'
what I want is the 1 to be named as the column name
You can iterate over array keys of first row to get column names. But better option is to use ORM schemes and get titles from there.
One solution (but not recomennded, because you must iterate over all columns you retrieve from table). And you show also ID column name.
echo '<div class="categories">' . implode(array_keys($row), ' - ') . '</div>';
Second thing is that your design of database is very bad. I don't know exact purpose but you should have for categories only two columns: ID and name.
after looking for the optimal table thanks to kerbh0lz and tajniak I found it
create table statement
create table categories (categoryid int(1), category varchar(20) );
inserting new genres
insert into categories values
(1 ,'action'),
(2 ,'comedy'),
(3 ,'drama'),
(4 ,'mystery');

Getting the missing IDs from a table by storing the records into an array and compare the set of numbers with a for loop

I'm currently working on a program that gets the missing IDs of a table and the idea that I come up with is that by storing the IDs into an array and use a for loop to check if a number exists in the array and if it's existing then it is classified as a missing ID. I also used the php function - in_array() to check if a number exists in the array.
This is the code that I came up with, but I ended up with just displaying the numbers from the for loop.
<?php
include 'dbconnect.inc'; //just to the the dbconnect for connecting into the database.
$numbers = array(1, 2, 4, 6, 7, 9);
$arrlength = count($numbers);
$query = "SELECT id FROM existing";
$result = mysqli_query($conn, $query);
$existing = array();
while ($row = mysqli_fetch_assoc($result)) {
$existing[] = $row;
}
for ($i=0; $i<7358; $i++) {
if (in_array($i, $existing)) {
echo $i . " is a missing ID <br>";
} elseif(!in_array($i, $existing)) {
echo $i . " exists in the table <br>";
}
}
?>
I prefer this solution than using the temporary tables in an SQL because it takes more than to load the query and it would not be good for a webpage.
Hope that you could help me. Thanks!
From this answer:
To get missing ranges:
SELECT a.id+1 AS 'Missing From', MIN(b.id)-1 AS 'Through'
FROM existing AS a
JOIN existing AS b ON a.id < b.id
GROUP BY a.id
HAVING a.id+1 < MIN(b.id)
fiddle
User variables are only evaluated when sent, so using a HAVING NOT (gap_from=0 AND gap_to=0) clause isn't possible as an optimization (see user variables manual). A such we use the "sending" to be sending to the temporary table to save a larger time full of data that is about to be discarded.
The temporary table uses the primary key ensure there will only be one (0,0) entry that occurs when the there is no gap. Inserting subsequent existing entries (0,0) gets ignored resulting in a minimal table of gaps.
The remainder of the table is the gaps in the sequence:
create table existing (id int unsigned not null)
insert into existing values (3),(5),(6),(7),(8),(19),(20),(21),(30)
set #last=0
CREATE TEMPORARY TABLE v (gap_from int unsigned, gap_to int unsigned, next int unsigned, PRIMARY KEY(gap_from, gap_to))
IGNORE SELECT IF(#last=id, 0, #last) as gap_from,
IF(#last=id, 0, id-1) as gap_to,
#last:=id+1 as next
FROM existing ORDER BY id
select gap_from,gap_to from v where NOT (gap_from=0 AND gap_to=0)
gap_from | gap_to
-------: | -----:
0 | 2
4 | 4
9 | 18
22 | 29
If you don't want the first gap, the one between 0 and the first entry in the table:
select gap_from,gap_to from v where gap_from!=0
db<>fiddle here

putting values in between the ascending database column

Following is my database in mysql:
Id Username Password
1 admin admin
2 jay jay1
3 suman xyza
4 chintan abcde
This is my code in php:
$fetchid = mysql_query(" SELECT MAX(Id) As max From user;");
$row = mysql_fetch_array($fetchid);
$largest = $row['max'];
$largest++;
$user= $_POST['username'];
$pass= $_POST['password'];
$result = mysql_query(" INSERT INTO `proshell`.`user` (
`Id` ,
`Username` ,
`Password`
)"."
VALUES (
'".$largest."', '".$user."', '".$pass."'
);");
Problem:
Now if I delete row with Id=1 and then re-enter the data then it should use ID=1 then Again I reinsert the data it use ID=5
It works like this:
if I delete row with Id=1 and then re-enter the data the Id it gets is 5 but then 1 is free so,
What should I write to perform that task.
First, if you set your Id column to AUTO_INCREMENT you don't need the following part in your code at all:
$fetchid = mysql_query(" SELECT MAX(Id) As max From user;");
$row = mysql_fetch_array($fetchid);
$largest = $row['max'];
$largest++;
Because AUTO_INCREMENT will automatic add new value to your ID colume.
But if you don't set it to AUTO_INCREMENT, the above code will grab the MAXIMUM ID value (in this case, 4).
When you re-enter your data again after you delete the row 1, the MAXIMUM ID still 4, so your new ID value will be 5 (from $largest++;).
.....
If you really need to use consecutive ids as you PK, you need to re-write you code but I suggest you to use UUID for you ID column instead.
You can easily generate UUID by using uuid().
How about the UUID performance? Refer to Dancrumb's answer about this:
A UUID is a Universally Unique ID. It's the universally part that you should be considering here.
Do you really need the IDs to be universally unique? If so, then UUIDs
may be your only choice.
I would strongly suggest that if you do use UUIDs, you store them as a
number and not as a string. If you have 50M+ records, then the saving
in storage space will improve your performance (although I couldn't
say by how much).
If your IDs do not need to be universally unique, then I don't think
that you can do much better then just using auto_increment, which
guarantees that IDs will be unique within a table (since the value
will increment each time)
see. UUID performance in MySQL?
EDIT: I don't suggest you run query on the whole table just to find the MAX ID value before inserting new value everytime, because it will give you a performance penalty (Imagine that if you have million rows and must query on them everytime just to insert a new row, how much workload causes to your server).
It is better to do the INSERT just as INSERT, no more than that.
EDIT2:
If you really want to use consecutive ids, then how about this solution?
Create new TABLE just for store the ids for insert (new ids and the ids that you deleted).
For example:
CREATE TABLE cons_ids (
ids INT PRIMARY KEY,
is_marker TINYINT DEFAULT 0
);
then initial ids with values from 1-100 and set marker to be '1' on some position, e.g. 80th of whole table. This 'marker' uses to fill your ids when it's nearly to empty.
When you need to INSERT new Id to your first table, use:
$result = mysql_query("SELECT ids, marker FROM cons_ids ORDER BY ids ASC LIMIT 1;");
$row = mysql_fetch_row($result);
and use $row[0] for the following code:
INSERT INTO yourtable (Id, Username, Password)
VALUES ($row[0], $username, $password);
DELETE FROM cons_ids
WHERE ids = $row[0];
This code will automatically insert the lowest number in cons_ids as your Id and remove it from the cons_ids table. (so next time you do insert, it will be the next lowest number)
Then following with this code:
if ($row[1] == 1) {
//add new 100 ids start from the highest ids number in cons_ids table
//and set new marker to 80th position again
}
Now each time you delete a row from your first table, you just add the Id from the row that you deleted to cons_ids, and when you do INSERT again, it will use the Id number that you just deleted.
For example: your current ids in cons_ids is 46-150 and you delete row with Id = 14 from first table, this 14 will add to your cons_ids and the value will become 14, and 46-150. So next time you do INSERT to your first table, your Id will be 14!!.
Hope my little trick will help you solve your problem :)
P.S. This is just an example, you can modify it to improve its performance.
First of all, as I understand, you are selecting highest column ID which should be always the last one (since you set auto-increment on ID column).
But what are you trying to do is actually filling up holes after delete query, right?
If you are really looking for such approach, try to bypass delete operation by making new boolean column where you flag record if it is active or not (true/false).
SQL table change:
Id Username Password Active
1 admin admin false
2 jay jay1 true
3 suman xyza false
4 chintan abcde true
PHP request:
$fetchid = mysql_query(" SELECT MIN(Id) As min FROM user WHERE active = false;");
$result = mysql_query(" INSERT INTO `proshell`.`user` (
`Id` ,
`Username` ,
`Password`
`Active`
)"."
VALUES (
'".$largest."', '".$user."', '".$pass."', 'true'
);");

inserting a field the a_i value of another field

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.

help in uniquely identifying combine columns

How can I uniquely identify two or more columns, that I have used table named address in the database, now address is has fields like street name, suite name and street num.
strnum | strnam | sutname
1 | xyz | 32
1 | xyz | 32
now how can I uniquely these three columns. That is I want to check whether these three column are already inserted or not. If any field valus is changed than its ok, it will insert new one. but in case all three similar field..Help me to combinely identify these three fields.
You do it by adding unique constraint.
ALTER TABLE your_table ADD UNIQUE(strnum, strnam, sutname);
Then you do the following:
INSERT IGNORE INTO your_table (strnum, strnam, sutname) VALUES ('1', 'xyz', 'etc');
If the value exists already - no insert will happen and no errors will be raised (that's what the IGNORE part is).
By the way why do you use such short and vague column names? It's not the DOS era any more, you can be descriptive with your column names.
$query = "SELECT * FROM `address` WHERE `strnum` = '$strnum' AND `strnam` = '$strnam' AND `sutname` = '$sutname' LIMIT 1";
$result = mysql_query($query);
if (!mysql_num_rows($result)) {
// If you get to here, there is no existing record
$query = "INSERT INTO `address` (`strnum`,`strnam`,`sutname`) VALUES ('$strnum','$strnam','$sutname')";
if (!mysql_query($query)) print('Insert failed!');
} else print('Record already exists!');
EDIT I just added a missing ; so this parses...
just add them as unique keys in table structure and you'll not be able to insert two of them
you can do something like this
SELECT * FROM table WHERE col1 = $something AND col2 = $something2 AND col3 = $something3
(remember about escpaing php variables)
if the record is returned it means it exists. You can also add LIMIT 1 to make it faster.
if your question is about ENSURING that no duplicates occur in the table (for those 3 columns), then probably the best solution is to add UNIQUE index on those three columns.

Categories