How can I update multiple rows in MySQL using one query? It has been asked before, I know, but I have no idea how to use the CASE expressions.
I currently have this:
$sql = "UPDATE " . $DBtable . " SET clicks = clicks + 1 WHERE id= :id";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();
How can I add a timestamp in the same query:
// Add timestamp
$date = new DateTime();
$now = $date->format('Y-m-d H:i:s');
"UPDATE " . $DBtable . " SET dl_time = ". $now . " WHERE id= :id";
dl_time is the name of the column.
You can set multiple columns in an update:
UPDATE " . $DBtable . "
SET clicks = clicks + 1,
dl_time = now()
WHERE id= :id;
Note that there is one set clause, with the assignments separated by commas.
Note that this version uses the database time rather than the application time. Unless you specifically want the application time, the database time makes the rows more consistent.
Related
I'm using PDO in PHP to connect to MySQL. My project is a chat app
Everytime someone sends a new message, I insert the message into table chat_messages, and I update a timestamp in table chat_users to indicate that that was the last time the user was active.
$sql = "INSERT INTO chat_messages
(email_sender, message, sent)
VALUES ('" . $email . "', '" . $message . "', '" . time() . "')";
$query = $pdo->prepare($sql);
if ($query->execute()) {
$sql2 = "UPDATE chat_users SET last_active = UNIX_TIMESTAMP()
WHERE email = '$email'";
$pdo->prepare($sql2)->execute();
// to test my query syntax is correct:
echo $sql2;
}
The timestamp is not being updated in the database. When i copy paste the output of echo $sql2 into phpMyAdmin, the query works.
What am i doing wrong?
Thank you
You're really missing out on a lot of the benefit of using prepared statements if you concat variables into the SQL like that. If you prepare with placeholders and bind your values, it will probably take care of your problems as well as being more secure against SQL injections.
$sql = "INSERT INTO chat_messages(email_sender, message, sent) VALUES (?, ?, ?)";
$query = $pdo->prepare($sql);
if ($query->execute([$email, $message, $time])) {
$sql2 = "UPDATE chat_users SET last_active = UNIX_TIMESTAMP() WHERE email = ?";
$pdo->prepare($sql2)->execute([$email]);
// to test my query syntax is correct:
echo $sql2;
}
If your query is failing (and even if it isn't) you should set PDO to throw exceptions when queries fail, so you'll get a descriptive error message as to what went wrong.
I have a table with a user id and a date, several users connect at the same time and only one user a day can do insert in the database.
I have a slow connection to the server and what it takes to do the select of the last entry, whether it has been today or not, since it can not be a primary key because the date can vary, sometimes it makes double registrations for the same day.
How can I do this so that this does not happen and I only insure an insert a day?
Thank you
Code:
<?php
$sql = "SELECT MAX(timestamp_pole) as last_pole FROM pole WHERE id_group = ". $id_grup;
$resultado = $mysqli->query($sql);
$resultado = $resultado->fetch_assoc();
$las_00 = date('Y-m-d');
$las_00 = strtotime($las_00);
if ($resultado['last_pole'] >= $las_00){
} else {
$sql = "INSERT INTO pole (timestamp_pole, id_user, id_group) VALUES (". $timestamp .",". $user['id'] .",". $id_group .")";
$mysqli->query($sql);
//return addslashes($sql);
if (isset($user['username']))
return "#". $user['username'] ." pole!";
else
return $user['name'] ." pole!";
}
?>
you can create unique index using (date, id_group) as key, by that way you can make sure that there isn't any duplicated date in same group. Also remember to implement try/ catch as running insert query.
There is some error when I am executing this php code:
$today = date("Y-m-d H:i:s");
$sql = "UPDATE `deposit_admin_report` SET `READING`=$item,`Timestamp`=$today WHERE `METER_NUMBER`='NP-1353-'";
Error:
UPDATE `deposit_admin_report` SET `READING`=395,`Timestamp`=2015-11-27 09:08:33 WHERE `METER_NUMBER`='NP-1353-'
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '09:08:33 WHERE `METER_NUMBER`='NP-1353-'' at line 1
The column Timestamp has a type "timestamp" and default is "null" in the mysql table.
Will appreciate if anyone could help me out.
Thanks in advance
here is what you need:
$today = date("Y-m-d H:i:s");
$sql = "UPDATE `deposit_admin_report` SET `READING`=$item,`Timestamp`='".$today."' WHERE `METER_NUMBER`='NP-1353-'";
Also there is another way:
Simply use NOW()
Like this:
$sql = "UPDATE deposit_admin_report SET READING='$item',Timestamp=NOW()
WHERE METER_NUMBER='NP-1353-'";
That's it :)
use MySQL NOW() or change this $item to this '$item'
$sql = "UPDATE `deposit_admin_report` SET `READING`='$item',`Timestamp`=NOW()
WHERE `METER_NUMBER`='NP-1353-'";
$today = date("Y-m-d H:i:s");
$sql = "UPDATE `deposit_admin_report` SET `READING`= '" . $item . "',`Timestamp`= '" . $today . "' WHERE `METER_NUMBER`='NP-1353-'";
It sees the space in your date as a seperate word, and not as value of your timestamp.
Also, it is way easier to just use NOW()
$sql = "UPDATE `deposit_admin_report` SET `READING`= '" . $item . "',`Timestamp`= 'NOW()' WHERE `METER_NUMBER`='NP-1353-'";
Date field accepts a string which you should enclose in single quotes.
$sql = "UPDATE `deposit_admin_report` SET `READING`= $item, `Timestamp`= '$today' WHERE `METER_NUMBER`='NP-1353-'";
The question is already answered. Would like to bring into notice the caveat of using NOW() in Master / Slave architecture.
If timezone of slave server is different than that of master, the timestamp value stored on master will be different than the one on slave.
Its recommended to use following steps:
date_default_timezone_set('UTC'); // UTC is an example
$today = date("Y-m-d H:i:s");
$sql = "
UPDATE `deposit_admin_report`
SET `READING`=$item,`Timestamp`='".$today."'
WHERE `METER_NUMBER`='NP-1353-'
";
I am creating a forum service ( https://www.orbitrondev.com/forum/ )
When someone creates a new thread it will execute:
// Example values
$UserID = 23123;
$ForumID = 1;
$ThreadName = 'Example title';
$sQuery = 'INSERT INTO threads (user_id, board_id, topic, time, lastPostUserId, lastPostTime)
VALUES ("' . $UserID . '", "' . $ForumID . '", "' . $ThreadName . '", "' . $time . '", "' . $UserID . '", "' . $time . '")';
The ID is in the column thread_id
Now I have to get the ID (thread_id) of the inserted row. So I can create a post, and to create a post I need the ID.
I thought about getting the last inserted thread id an adding 1 so I have the id, but SQL looks finer :P
How can I know the thread_id value for the newly inserted row?
You should use mysqli::$insert_id.
Where $mysqli is your connection;
$result = $mysqli->query($sQuery);
$lastid = $mysqli->insert_id;
Although you should use prepared statements when inserting data into the database.
Note: You need to have an auto incremented ID field in the database for this to work.
You have;
$oResult = $Database->query($sQuery);
$ThreadID = $oResult->insert_id;
which will not work.
You should use the connection to find the last inserted ID, like this;
$oResult = $Database->query($sQuery);
$ThreadID = $Database->insert_id;
Hope this helps.
You can retrieve the most recent AUTO_INCREMENT value with the
LAST_INSERT_ID() SQL function or the mysql_insert_id() C API function.
These functions are connection-specific, so their return values are
not affected by another connection which is also performing inserts
http://dev.mysql.com/doc/refman/5.1/en/example-auto-increment.html
mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated id
used in the last query
http://php.net/manual/en/mysqli.insert-id.php
$tSQL = "insert into events(title,start,end,allday,url,customerid) VALUES(\"" . $_POST['title'] . "\", FROM_UNIXTIME($epochstart), FROM_UNIXTIME($epochend), \"$allday\", \"$url\", \"$customerid\")";
$mysqli->multi_query($tSQL);
$lasterror = $mysqli->error;
$tSQL = "update events set url = \"details.php?\"" . mysql_insert_id() . " where idevents = \"$eventid\"";
$row = $mysqli->multi_query($tSQL);
$lasterror = $mysqli->error;
echo print_r($tSQL);
My insert statement for sure does insert the record however mysql_insert_id() keeps returning 0. It should not be this way because there is an auto incremented primary key in that events table and that is running fine as well. Any suggestions on how to get the last inserted ID?
Your query is executed via mysqli, so the mysql function would not hold the inserted ID. Instead, use the mysqli version:
$id = $mysqli->insert_id;
Becasue you are using mysqli and not mysql,
Simply replace mysql_insert_id() with mysqli_insert_id() if using Procedural style
Or replace it with $mysqli->insert_id if using Object Oriented Style
Since you are using mysqli extension, change
$tSQL = "update events set url = \"details.php?\"" . mysql_insert_id() . " where idevents = \"$eventid\"";
to
$tSQL = "update events set url = \"details.php?\"" .$mysqli->insert_id. " where idevents = \"$eventid\"";
Because your are using mysqli which is an improvement version of mysql.
Use mysqli->insert_id instead of mysql->insert_id()
$tSQL = "insert into events(title,start,end,allday,url,customerid) VALUES(\"" . $_POST['title'] . "\", FROM_UNIXTIME($epochstart), FROM_UNIXTIME($epochend), \"$allday\", \"$url\", \"$customerid\")";
$mysqli->multi_query($tSQL);
$lasterror = $mysqli->error;
$lastInsId=$mysqli->insert_id();
$tSQL = "update events set url = \"details.php?\"" . $lastInsId . " where idevents = \"$eventid\"";
$row = $mysqli->multi_query($tSQL);
$lasterror = $mysqli->error;
echo print_r($tSQL);