Jump to content

Can you use substr in a MySQL query?


galvin

Recommended Posts

I have a MySQL table with a "dob" field that stores specific dates and times.  The data is in this format, for example...

 

2011-02-03 14:08:00

 

I want to retrieve the unique YEAR values, as efficiently as possible. I came up with the code below which doesn't work. So my assumption is that you are not able to use "substr" within a MySQL query. Is that right?

 

If so, can someone guide in the direction of the best way to achieve this.  I guess I have to just bring back all the dob FULL values into an array, but then not sure how to get just the year (first four characters) and only the UNIQUE ones, since many will be the same year.

 

Or if you actually CAN use "substr" within a MySQL query, then I must have screwed something else up, so let me know what else I might have done wrong.

 

 

$sql = "SELECT distinct substr(dob,0,4) AS year FROM info
WHERE id = '{$_GET['id']}'";
$getyear = mysql_query($sql, $connection);
if (!$getyear) {
die("Database query failed: " . mysql_error());
} else {
	while ($years = mysql_fetch_array($getyear)) {
		echo "Years=" . $years['year'];
	}
}

 

Link to comment
Share on other sites

Thanks Pikachu2000.  I apologize for being a bigtime newbie with MySQL functions but can I stick that function IN the query, or do I call it somewhere else?

 

I tried this, which is obviously not correct :-\

 

$sql = "SELECT distinct DATE_FORMAT('dob','%Y') AS year FROM data
WHERE id = '{$_GET['id']}'";
$getyear = mysql_query($sql, $connection);
if (!$getyear) {
die("Database query failed: " . mysql_error());
} else {
	while ($years = mysql_fetch_array($getyear)) {
		echo "Years=" . $years['year'];
	}
}

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.