I have an issue with structuring my data correctly. I have over 6000 rows in it, but because of some error it is overwriting my existing rows!
I think I have many values in the columns which are same, that is why he is overwriting my existing rows.
Datatable structure
Datatable info
My columns:
bid - primary key, which is auto increment
btyp - can have values 1,2 or 3 only
mid - can have values 1-300 only
monat - month - 1-12 only
jahr - year - 2016 upwards only
language - has values "de" or "ur" only
entry_date - date
entry_type - has values 1 or 2 only
entry_uid - 10-15 different values
upload_date - date
upload_uid - 10-15 different values
zusatz - some text
The columns mid,monat,jahr & btyp should be unique together in the datatable. So if I want to save a new record, I have to first check whether I have already that row in my database. If not, it should be inserted. If yes, updated. I am trying to do this:
$checker2="SELECT * FROM berichte WHERE mid='".$_POST['mid']."' AND monat='".$_POST['monat']."' AND jahr='".$_POST['jahr']."' AND btyp='".$btyp."'";
$checkresult2 = mysqli_query( $mysqli, $checker2 );
if (mysqli_num_rows($checkresult2)>0) {
$sql3 = "UPDATE berichte SET (entry_date = '" . $jetzt . "') WHERE mid='".$_POST['mid']."' AND monat='".$_POST['monat']."' AND jahr='".$_POST['jahr']."' AND btyp='".$btyp."'";
} else {
$sql3 = "INSERT INTO berichte(btyp, mid, monat, jahr, language, entry_date, entry_type, entry_uid, upload_date, upload_uid, zusatz)
VALUES (".$btyp.",'".$_POST['mid']."','".$_POST['monat']."','".$_POST['jahr']."','de','" . $jetzt . "','1','1','" . $jetzt . "','1','Online Eintragung von Majlis')";
}
mysqli_query( $mysqli, $sql3 );
}
But as I mentioned, there seems to be an issue I am not getting. Some rows are overwritten.
I hope anybody can help here.
Related
Trying to basically re-count the primary column, meaning updating from the first to the last, incrementing the value with each row. First I am selecting,
select
`someid`,
`time`
from
`table`
ORDER BY
`time` ASC
fetching the result,
$data = new SplFixedArray($query->num_rows);
$data = $query->fetch_all();
and updating the table.
for($i=1; $i<count($data); $i++){
print_r("UPDATING | New someid: " . $i . " WHERE old someid: " . $data[$i][0] . " AND time = " . $data[$i][1] . "<br />");
$query = $mysqli->query("UPDATE `table` SET `someid` = '" . $i . "' WHERE `time` = '" . $data[$i][1] . "' AND `someid` = '".$data[$i][0]."'");
}
What confuses me is, that the first few entries aren't sorted correctly. It's like
someid | time
--------------
0 | 0
2 | 1
1 | 2
7 | 3
11 | 4
6 | 5
It's because of duplicates. After the 15ish rows in "someid" there is a gap and it jumps to 60. So after that there are no more duplicate someids. But how can I handle the first few rows? If I want to update someid to 2 but 2 is already existent?
Any way to handle that without using too many querys?
Edit:
Maybe it's unclear to some. Basically I am trying to refresh the int-values from a primary column. So basically I am counting them and enter their appropriate number into someid, sorted by sometime. Sometime is datetime. So the earliest "sometime" would get "someid" = 1.
At the moment, someid has gaps. 1..2..3..4..5..6..7..15..16..17..18..30..31..32
Updating, like I am doing now, doesn't work until I reach a gap. Because I am trying to write a duplicate value. Updating the first someid to 1, which might be of value 11, does not work because someid 1 is already existent somewhere.
I would update someid 15 to 8, because it's the next number. This works because 8 to 14 are missing, and I am not duplicating a value.
One solution might be to create another loop and first update every someid to some made up number, maybe start counting from row->count, incrementing for every row. After that, I can update them as I'd do normally. But isn't there a better solution?
// UPDATE:
This:
SET #count = 0;
UPDATE `table` SET `table`.`someid` = #count:= #count+ 1;
"Resets" the IDs, but it doesnt sort them by time.
Trying this:
SET #count = 0;
UPDATE `table` SET `table`.`someid` = #count:= #count+ 1;
ORDER BY `time` DESC;
Gives me the following error:
Duplicate entry '1' for key 'PRIMARY'
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
I'am trying to implement a "most popular searches" function on a web site using a simple counter. The idea is that the first time a search is made, the query is stored in a special table. After that the count number increments by one every time that same search is made. I think I do exactly as I should but the code doesn't seem to work. The count value stays on NULL in the table. Here's my code. "Searchny" is the table where I store the searches. Any pointers much appreciated!
$search_result = mysql_query("SELECT * FROM searchny WHERE sok='$sokt'");
if(mysql_num_rows($search_result) == 0 ) {
$sql = "INSERT INTO searchny (sok, dt) VALUES ('" . $sokt . "', NOW());";
mysql_query($sql);
}
else {
mysql_query("UPDATE searchny SET count = count+1 WHERE sok='$sokt'");
}
Probably your count column is NULL by default and every count+1 doesn't make it any less NULL. Try either setting default value of one or explicitly set it to one in INSERT.
Your code has no mistake, so the problem isn't the code.
Is your value NULL or 0 ?
If it is NULL, change
INSERT INTO searchny (sok, dt) VALUES ('" . $sokt . "', NOW());
to
INSERT INTO searchny (sok, dt, count) VALUES ('" . $sokt . "', NOW(), 0);
Your problem is most likely that count is NULL. Anything added to NULL is NULL.
Try this query:
SELECT NULL + 1
The result will be:
NULL
You could set your default value for the count field to 0 instead.
However, here's a simpler way to implement this. Note that I've excluded the date field because I don't know what the requirements for the date are:
Table searchny:
---------
sok
count
---------
primary_key (sok)
Then do it all in one statement:
INSERT INTO searchny (sok, count) VALUES ($sokt, 1)
ON DUPLICATE KEY UPDATE count = count + 1
If it's a new sok value, then a new row is inserted and the count is set to 1. If the sok value already exists, then the record's count is incremented by 1.
TABLE:
09:00 -- id_timeslot = 1
09.15 -- id_timeslot = 2
09.30 -- id_timeslot = 3
09.45 -- id_timeslot = 4
10.00 -- id_timeslot = 5
PHP MYSQL:
for($i=0; $i<=2; $i++) {
$mysqli->query("INSERT INTO bookslot(id_timeslot, id_member, b_ref, id_doctor, status)
VALUES ('" . ++$id_timeslot . "', '" . $id_member . "', '" . $b_ref . "', '" . $id_doctor . "', 1)" )
}
I want the data to be saved twice and increment the id_timeslot.
The above code working fine, but when save cliked. it didnt pick up the right id_timeslot?
for example: if user click on id_timeslot:1, soon it save to database the id_timeslot starts from 2 instead of id_timeslot 1?
if user click on id_timeslot:1, soon it save to database the id_timeslot starts from 2 instead of id_timeslot 1?
This is because you're using a pre-increment rather than a post-increment. If $id_timeslot is 1 before entering the loop, the value of ++$id_timeslot is 2, so the first generated query is:
"INSERT INTO bookslot(id_timeslot, id_member, b_ref, id_doctor, status)
VALUES ('2', '$id_member', '$b_ref', '$id_doctor', 1)"
If the id_timeslot column is supposed to be an ID for the bookslot record, the best approach is to declare it with the AUTO_INCREMENT attribute and don't insert values for that column:
-- run just once in some MySQL client
ALTER TABLE bookslot MODIFY id_timeslot INT UNSIGNED PRIMARY KEY AUTO_INCREMENT;
// in PHP
$stmt = "INSERT INTO bookslot(id_member, b_ref, id_doctor, status)
VALUES ('$id_member', '$b_ref', '$id_doctor', 1)";
When using double quoted strings, you don't need to concatenate variables. Compare the above statement with your own.
If id_timeslot isn't a unique ID, then you can simply switch to post-increment.
$stmt = "INSERT INTO bookslot(id_timeslot, id_member, b_ref, id_doctor, status)
VALUES (" . $id_timeslot++ . ", '$id_member', '$b_ref', '$id_doctor', 1)";
This may or may not be a correct approach for various other reasons. Without knowing more about the schema, it's impossible to say.
Off Topic
Depending on where the values for $id_member, $b_ref $id_doctor originate, your script could be open to SQL injection. Rather than inserting values directly into the string, use a prepared statement. MySQLi supports them, as does PDO, which is simpler to use. New code should use PDO, and old code should get updated over time.
You have to fetch last id_timeslot from database and then increase it PHP during inserting.
I'm building a database for making hotel reservations. One table called "reservations" holds the general details of the reservation, while another called "rooms" holds details about specific rooms (each reservation has many rooms, each room belongs to only one reservation).
I would like to be able to easily generate duplicate reservations records (except for the primary key, of course). My problem is in generating the rooms data as an array which is then inserted into the rooms table while being associated to its reservation.
I've come as far as the following trivial code (stripped down to the bare essentials for discussion purposes).
if (isset($_POST['action']) and $_POST['action'] == 'Duplicate')
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/connect.inc.php';
$id = mysqli_real_escape_string($link, $_POST['id']);
// retrieve reservation
$sql = "SELECT type_of_reservation FROM reservations WHERE id='$id'";
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
$type_of_reservation = $row['type_of_reservation'];
// create new reservation record
$sql = "INSERT INTO reservations SET type_of_reservation ='$type_of_reservation'";
$id = mysqli_insert_id($link);
// retrieve rooms
$sql = "SELECT reservation_id, in_date FROM rooms WHERE reservation_id='$id'";
$result = mysqli_query($link, $sql);
while ($row = mysqli_fetch_array($result))
{
$rooms[] = array('reservation_id' => $row['reservation_id'], 'in_date' => $row['in_date']);
}
The big question is, now what? Everything I've tried either generates an error or no new entries, and I can't seem to find any discussion that addresses this specific need. Thanks for your help.
PeterC, there is no code listed that shows you inserting the ROOM record information. In the //retrieve room section of your code, you are pulling the data and putting it into an array. If you really want to create a duplicate records, I would use in insert inside the database, then you don't have to pull the records out just to put them back in.
The bit of code you want will be something like this. It will be in place of the //retrieve rooms code you have listed: (psuedo code) [note: $id represents the newly selected id from your sql insert for the duplicated reservation]
INSERT INTO rooms(res_id, other, data)
SELECT $id, other, data FROM rooms WHERE id = $_POST['id'];
This will allow you to duplicate the room data, adding the new reservation_id right inside the database. No need to pull out the records, create inserts, and then put them back in. You can read more about INSERT INTO ... SELECT statements here: http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-select-into-table.html
// create new reservation record
$sql = "INSERT INTO reservations SET type_of_reservation ='$type_of_reservation'";
//ADD HERE CODE BELOW
$id = mysqli_insert_id($link);
with mysql_insert_id you get the inseted id, but you should insert it into db.. so add
mysqli_query($link, $sql);
before retrieving data
If you simply need to duplicate records, you can do it this way:
INSERT INTO
reservations
(
SELECT
null, # assume first column is auto incrementing primary key, so leave null
`all`,
`other`,
`column`,
`names`
FROM
reservations
WHERE
reservation_id = $oldReservationId # id of reservation to duplicate
)
Then for the rooms use the last inserted id (for instance retrieved with mysql_insert_id), like this:
INSERT INTO
rooms
(
SELECT
null, # assume first column is auto incrementing primary key, so leave null
$newReservationId, # this is the new reservation id
`all`,
`other`,
`column`,
`names`
FROM
rooms
WHERE
reservation_id = $oldReservationId # id of reservation to duplicate
)