Subtracting two datetime values - sql

I'm trying to get the length of time a user was logged in for. My code is grabbing the login and logout time but the loginLength field in my DB table isn't updating with this code. Any ideas what's wrong with it?
$logout = "UPDATE Emp
SET loginStatus = 0,
LogoutTime = NOW()
WHERE username = '$_SESSION[username]'";
if (! mysql_query($logout))
{
echo "Error" . mysql_error();
}
$time = "UPDATE Emp
SET loginLength = DATEDIFF(milliseconds,LoginTime,LogoutTime)
WHERE username = '$_SESSION[username]'";
if (! mysql_query($time))
{
echo "Error" . mysql_error();
}

I suspect you are using MySQL as your database (the obsolete "mysql_" functions are a hint). You are then using SQL Server syntax for the date operations.
The MySQL equivalent is:
UPDATE Emp
SET loginLength = TIMESTAMPDIFF(MICROSECOND, LoginTime, LogoutTime) / 1000
WHERE username = '$_SESSION[username]';
You can try "MILLISECOND", but it is not documented as working.

Related

How PhpStorm can recognize incomplete SQL query for check syntax and validation?

When I use full PDO query:
$db = DB::singleton();
$stmt = $db->prepare("SELECT * FROM promocode WHERE status = 1 AND code='xyz'");
$stmt->execute();
PhpStorm recognize table scheme and it suggests syntax & show wrong column name - Nice!
...but, most often I use db like this:
public function get($coupon)
{
/* table:promocode */
$db = $this->db()->retObj();
$db->where('status = 1 AND code = ?', [$coupon]);
return $db->fetch();
}
Is there any "magic" comment like (table:promocode) to tell PhpStorm that it is DB syntax?

SQL update not running, reasons unknown

I am trying to run an update and for reasons I cannot figure out why it is not running.
The error:
Failed to run query: SQLSTATE[42000]: Syntax error or access violation: 1064 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 'WHERE EventID = '2'' at line 4
I cannot figure out what is wrong with the syntax.
$query = "
UPDATE event
SET AssignedTo = '$AssignedTo',Project = '$Project',Category = '$EventCategory',
Status = '$Status',Services = '$EventServices',Priority = '$EventPriority',
WHERE EventID = '$ID' ";
try {
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex){ die( "Failed to run query: " . $ex->getMessage()); }
die("                      Changes Submitted");
}
This requires formatting the text, so it is too long for a comment.
If you format your queries neatly, then you can avoid or at least minimize such problems:
UPDATE event
SET AssignedTo = '$AssignedTo',
Project = '$Project',
Category = '$EventCategory',
Status = '$Status',
Services = '$EventServices',
Priority = '$EventPriority',
-------------------------------------^
WHERE EventID = '$ID';
The lines for the query don't scroll off the page, making it easier to spot an extra comma.

JAVA - getTime() from DB - always getting 01:00:00

I have this code for selecting time from my database (SQLite):
String sql = "select cas from mytable where id = 'S222'";
Statement stmt2;
try {
stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
Time cas = rs.getTime("cas");
System.out.println(cas.toString());
}
} catch (SQLException ex) {
...
}
I am always getting value: 01:00:00 and in the database, there is a time set to 09:10:00
When I run this sql select statement in database by "execute command" I get right value. But when I run it from java application, it always prints 01:00:00. What is the problem? When I am selecting something else, not time, it is correct.
And I tried following select:
String sql = "select cas from mytable where id = 'S222' and cas = '09:10:00'";
And it also prints 01:00:00
I solved it!
instead of:
Time cas = rs.getTime("cas");
I used:
String cas = rs.getString("cas");
and it works. TY

Sql Select If Statement not working but working as simple function without if statement

Need help, am trying to use Select if statement in Sql
$sql = "Select *,
(select prod_name from #__mobile_products where prod_id=z.z_prod_id)
as cell_name from #__mobile_types AS z
When z.z_status='1' and z.z_id = '".$vid."'
else JError::raiseError(404, "Message");
";
Target Objective is: show list when z_status=1 and display J Error when z_status=0. However it's not working. This function works well
$sql = "Select *,
(select prod_name from #__mobile_products where prod_id=z.z_prod_id)
as cell_name from #__mobile_types AS z
Where z.z_status='1' and z.z_id = '".$vid."'
";
However when trying to modify using else statement it does not work.
Edit - Complete Function Code:-
$database =& JFactory::getDBO();
global $Itemid;
$sql = "Select *,
(select prod_name from #__mobile_products where prod_id=z.z_prod_id)
as cell_name from #__mobile_types AS z
Where z.z_status='1' and z.z_id = '".$vid."'
";
$database->setQuery($sql);
$rows = $database->loadObjectList();
return $rows[0];
You are confusing SQL and PHP and Joomla: The second query you wrote is the one you want to run. But the logic needs to be handled in php. Your sql engine doesn't know "else" (which is php) or JError (which is Joomla). Not to speak about the wrong use of " - as you wrote it's just a syntax error.
$db = JFactory::getDbo();
$sql = "Select *,
(select prod_name from #__mobile_products where prod_id=z.z_prod_id)
as cell_name from #__mobile_types AS z
Where z.z_status='1' and z.z_id = " . $db->quote($vid);
$db->setQuery($sql);
if ($result = $db->loadObject()) {
// the query returned something, you can use the result object
echo $result->prod_name;
} else {
if ($db->getErrorNum()) {
JError::raiseError(500, "Something went horribly wrong, the query returned the error ". $db->getErrorMsg());
} else {
echo "Your query returned no records i.e. no records satisfy the z_status=1 condition";
}
}
Finally, 404 is "not found", but it refers to the request, not the data in your application. You might want to return 500 if the query errors out, and 200 for all other requests. See here for more info on status codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

Two separate database queries to relate separate tables with Drupal 7 module?

I am developing a custom module for a site I'm working on and have created the following code. This is my first module, so any ideas of what I could be doing better would be appreciate.
As it is, this module works perfectly for me. But, I want to optimize it and be sure that I fix shoddy code.
Thanks!
The function in question is as follows:
// Declared variables for future incrementation
$total=0;
$countOne=0;
$countTwo=0;
$countThree=0;
$countOld=0;
// Call the native global user object from Drupal
global $user;
$userID = $user->uid;
// Check for nodes of given type owned by current user
$sql = db_query("SELECT nid FROM {node} WHERE type = 'content_type' AND uid = " . $userID);
// Iteratively checks each node id against a custom Drupal field on a separate table
foreach ($sql as $record) {
// SQL query for all custom fields attached to the node id given above
$query = db_query("SELECT * FROM {field_birth} WHERE entity_id = " . $record->nid);
$result = $query->fetchObject();
// The unmodified birth format (Y-m-d 00:00:00)
$originalBirth = $result->field_date_of_birth_value;
// The sanitized birth format for comparison (Y-m-d)
$birth = date('Y-m-d', strtotime($originalBirth));
// The current date/time (Y-m-d)
$now = date('Y-m-d');
//Future dates (Y-m-d)
$one_year = date('Y-m-d', strtotime('+1 year', strtotime($birth)));
$two_years = date('Y-m-d', strtotime('+2 years', strtotime($birth)));
$three_years = date('Y-m-d', strtotime('+3 years', strtotime($birth)));
// A count of all records returned before logical statements
$total++;
// Logic to determine the age of the records
if($now < $one_year) {
$countOne++;
}
else if($now >= $one_year && $now < $two_years) {
$countTwo++;
}
else if($now >= $two_years && $now < $three_years) {
$countThree++;
}
else {
$countOld++;
}
My question is, can I avoid having two separate database queries to hit both tables? I am not really sure how to go about that. Also, am I doing things in a manner which will be resource intensive and highly inefficient? As I am not a programmer by trade, I am not certain when code is 'good'. I do want to try my best to make this good code though since it is a module for a website I hope will last a long time.
Thank you stackoverflow community!
EDIT: The code I got working thanks to Mike is as follows. If anyone has a similar question / problem hopefully this will help!
// Join field_birth_table to nodes of given type owned by current user
$sql = db_select('node', 'n');
$sql->join('field_birth_table', 'b', 'n.nid = b.entity_id');
$sql
->fields('b', array('field_birth_field_value', 'entity_id'))
->condition('n.type', 'content_type')
->condition('n.status', '1')
->condition('n.uid', $user->uid)
->addTag('node_access');
$results = $sql->execute();
You can use a left join between the node and field_birth table:
$query = db_select('node', 'n');
$query->leftJoin('field_birth', 'b', '(b.entity_id = n.nid AND b.entity_type = :node)', array(':node' => 'node'));
$query
->fields('b', array())
->condition('n.type', 'content_type')
->condition('n.uid', $user->uid)
$results = $query->execute();