Counter in mysql doesn't work - php

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.

Related

Maria DB SQL Insert INTO ON DUPLICATE working only for first updated value

I am using this http://www.phpzag.com/create-live-editable-table-with-jquery-php-and-mysql/ as a template for editing two columns in my table. The edited entries are saved in new SQL table and called by unique key identifier back.
With each edit where the ID does not exist in the SQL I need the ID to be created so instead just UPDATE:
UPDATE notes SET $update_field WHERE shop_order='" . $input["SHOP_ORDER_NO"] . "'"
statement in SQL I want to check if ID exist and if so, to just update edited value otherwise create ID and update value. The update statement above works when ID is created.
Code below update just the "priority" value, not the note when edited. Also when I edit "note" it will not create new ID. I tried to figure it out for half a day without success.
<?php
include_once("db_connect.php");
$input = filter_input_array(INPUT_POST);
$poznamka = $input['note'];
if ($input['action'] == 'edit') {
$update_field='';
if(isset($input["priority"])) {
$update_field.= "priority='".$input["priority"]."'";
} else if(isset($input["note"])) {
$update_field.= "note='".$input["note"]."'";
}
if($update_field && $input["SHOP_ORDER_NO"]) {
$sql_query = "INSERT INTO notes (shop_order,priority,note)
VALUES ('" . $input["SHOP_ORDER_NO"] . "','" . $input["priority"] . "','" . $input["note"] . "')
ON DUPLICATE KEY UPDATE $update_field ";
mysqli_query($conn, $sql_query) or die("database error:".mysqli_error($conn));
}
}
?>
That link is missing some things, like a PRIMARY KEY. And IODKU depends on a UNIQUE key, which is usually a different column.
Your statement will act on only row, assuming there is only one duplicate value for some UNIQUE key. Please provide SHOW CREATE TABLE and the generated SQL so we can point out specifics.
Read the online docs about using ... UPDATE id = LAST_INSERT_ID(id) as a kludge for getting the new or old auto_increment id.
If you need to apply IODKU to multiple rows, see the syntax
INSERT INTO t (col1, col2, ...)
ON DUPLICATE KEY UPDATE ...
SELECT ((multiple rows from somewhere else));
However, this cannot provide the auto_increment ids for each new/existing row.

Recommendation of structuring my data in mysql - primary key - rows overwritten

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.

Update primary key, sorted by another column, duplicate handling?

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'

Insert data with MAX(id) and values of status at the same time

I was trying with this code but it didn't work. it's always get the MAX(eq_no) as 0
$sql1 =mysqli_query($con, "SELECT MAX(eq_no) AS val FROM tech_add_equip");
$sql2 = "INSERT INTO time (eq_no,status_no) VALUES ('$val', 4 );";
if (!mysqli_query($con,$sql2)) {
die('Error: ' . mysqli_error($con)); };
Finally, after I try with this code, it inserts in the right number of MAX(eq_no) but i still cant insert the values of status_no
INSERT INTO time (eq_no) SELECT MAX(eq_no) AS vale FROM tech_add_equip
Could you suggest me what did i missing in the code?
Thank you for your helping
One row returned from SELECT a,b,c statement in sub query is equivalent to set of values that is otherwise hardcoded as ('a-value','b-value','c-value')*. You can hardcode a value within select as well:
INSERT INTO time (eq_no, status_no)
SELECT MAX(eq_no), 4
FROM tech_add_equip
No need for aliases within select - order of columns matters.
*) One row result can be used for IN() clause. Another row would become set of values after comma - can't be uset for IN(), but it works ok for INSERT
('row1-a-value', 'row1-b-value'), ('row2-a-value', 'row2-b-value')
$max = SELECT MAX( customer_id ) FROM customers;
INSERT INTO customers( customer_id, statusno )
VALUES ($max , 4)

php mysql save mysql with for loop

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.

Categories