W
W
w_b_x2015-10-21 13:39:28
MySQL
w_b_x, 2015-10-21 13:39:28

MYSQL - Why does update update two values ​​instead of one?

Good day!
I have PHP code. It finds the "oldest" record in the database, namely the record that has the oldest date in the "last" column of the datetime type compared to the others. Takes the ID of this entry and updates its date to the current date.
However, no matter how I twisted this code and did not torture it, it changes the date not for one record, but for all that fit the status=1 description. How to fix it and why is this happening?

//Получаем из БД самую старую запись
$sql1 = mysql_query("SELECT `id` FROM advert WHERE status=1 ORDER BY last LIMIT 1"); 
//Проверяем есть ли вообще записи подходящие под описание
if(mysql_num_rows($sql1) != 0){
//Создаем ассоциативный массив найденной записи
$adata = mysql_fetch_assoc($sql1);
//Задаем переменную с нынешним временем
$now = date("Y-m-d H:i:s");
//Меняем дату у найденной записи
mysql_query("UPDATE advert SET last = '".$now."' WHERE id=".$adata['id']);
}

PS If I execute the query "SELECT `id` FROM advert WHERE status=1 ORDER BY last LIMIT 1" through PhpMyAdmin, then I get one single entry, which I need.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
W
w_b_x, 2015-10-21
@w_b_x

Fulfilled your request through SQL - everything works correctly. As soon as I do it via php:

mysql_query("UPDATE `advert` 
    SET `last` = NOW() 
    WHERE `status` = 1 
    ORDER BY `last` 
    LIMIT 1");

Changes two at once 0_o. What's wrong?
30843530c16742ecbd441062701bb991.png

P
Polycarp the Boreman, 2015-10-21
@NTP

This is done in one SQL query:

UPDATE advert
SET last = NOW()
WHERE id = (
    SELECT id
    FROM advert
    WHERE status = 1
    ORDER BY last
    LIMIT 1
)

R
Rsa97, 2015-10-21
@Rsa97

How about just doing it?

UPDATE `advert` 
    SET `last` = NOW() 
    WHERE `status` = 1 
    ORDER BY `last` 
    LIMIT 1;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question