I'm trying to create a query that takes the users input from a text field called $incorporation_date.
Query Idea
$sql = "SELECT * FROM companies WHERE incorporation_date LIKE '%%%%/%%/%%" . $incorporation_date . "%%%%/%%/%%'";
How would I make it so that you could use SQL to bring up the values of the submitted format you enter.
Example search 2015-06-15
Use a Date or Datetime and spare yourself of the grief that would otherwise follow were it not
drop table theGuy;
create table theGuy
(
id int not null auto_increment primary key,
fullName varchar(60) not null,
birthDate date not null
);
insert theGuy (fullName,birthDate) values ('Kim Smithers','2002-3-1'),('John Doe','2014-4-5');
select * from theGuy where birthDate>='2000-1-1' and birthDate<='2007-12-31';
select * from theGuy where birthDate between '2000-1-1' and '2007-12-31';
select *,birthDate+interval 45 DAY as BirthCertAvail from theGuy;
select *,datediff(curdate(),birthDate) as DaysAlive from theGuy;
You might find the built-in routines adequate, such as intervals, without having to rewrite them. ;)
Related
I'm new on php and mysql. I found several things that I can use - such as implode- on internet but I couldn't make it. I will try to be clear as much as I can.
First table name: mylist
column name: id (The values on this column are unique.) (incremental)
I put all ids inside an array called myIds. The array contains only unique integer values and it's length is 800.
I need to get answers for each ids from another table for the current date. This table also contain id column but for an id, there can be more than one answer.
For example: today, there are 3 answers for id 1 and 5 answers for id 4, etc.
Second table name: answerlist
This is the query works for a specified id:
$sql = "SELECT `answer` FROM `answerlist` WHERE `type`= 'Help' AND `id` = 1 AND DATE(`added`) = DATE (NOW())";
I would like to create a dynamic query which gets id values from the above array. How can I do this?
A Solution would be to use The mysql IN operations for your ids
SELECT `answer`, `id` FROM `answerlist` WHERE `type`= 'Help' AND `id` IN (1,2,3,4,5) AND DATE(`added`) = DATE (NOW())
you can implode them like this :
$sql = "SELECT `answer`, `id` FROM `answerlist` WHERE `type`= 'Help' AND `id` IN (" . implode(',', $myIds) . ") AND DATE(`added`) = DATE (NOW())";
I'm trying to create a script for stats about visitors to my site. To do this, I record the visitor's IP, along with the date of the day and the number of times it has passed.
If this is the first visit, on all records in the database. But I want to count 1 pass per person per day.
What I am trying to do : If the IP already exists, and the date is different from the day : we assign the date of the day, and increment the number of passing (+1).
The Problem : When the date is different from the day, it is changed, BUT: the number of passing continues to increment even if the IP has already been counted that day.
It should only be done the next day, when the date changes...
Here is my table structure :
--
-- Table structure for table `ChartsGuests`
--
CREATE TABLE `ChartsGuests` (
`IP_Guest` varchar(39) NOT NULL,
`Date` varchar(10) NOT NULL,
`Total` int(11) NOT NULL,
PRIMARY KEY (`IP_Guest`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB DEFAULT CHARSET=utf8;
Here is the code :
$IP_NewGuest = $_SERVER['REMOTE_ADDR'];
$Today = date('d/m/Y');
$SQL = "INSERT INTO `ChartsGuests` (`IP_Guest` , `Date`, `Total`) VALUES ('".$IP_NewGuest."' , '".$Today."', 1)
ON DUPLICATE KEY UPDATE
Date = IF(Date != '".$Today."', VALUES(Date), '".$Today."'),
Total = IF(Date != '$Today', VALUES(Total), Total + 1 )";
$REQ = $DB->prepare($SQL);
$REQ->execute() or die(var_dump($REQ->errorInfo()));
// echo $SQL;
It should only be done the next day, when the date changes... I do not know where the problem comes from, and this is the first time I use the "ON DUPLICATE KEY" with an "IF" ...
Thank you in advance !
Your problem is that your duplicate key is just on the IP address, but your table is really unique per IP Address/Date combo. As a result, visits on subsequent days overwrite the rows for the previous day.
If you change the logic of your table to have composite unique key on those two fields, the query will generate inserts for new (IP,Date) combos, and updates for (IP,date) combos that have been seen already.
If you fix that, you don't need the conditional (nor PHP for the current date), and you can just make this your SQL:
INSERT INTO `ChartsGuests` (`IP_Guest` , `Date`, `Total`)
VALUES ('".$IP_NewGuest."' , CURDATE(), 1)
ON DUPLICATE KEY UPDATE Total = Total + 1 )";
is there a way to get default values of columns as they are a row of a resultset?
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`state` tinyint(2) NOT NULL DEFAULT '22',
`pubdate` datetime NOT NULL DEFAULT '2012-01-01 00:00:00',
for instance a table like this should return this record:
id->NULL (?)
state->22
pubdate->2012-01-01 00:00:00
in practice, when some user opens edit.php?id=44 he will get the row 44 (update mode), but if he opens edit.php?id=0 (insert mode) I want that the fields contain default values as place holders
thank you in advance
There is a DEFAULT function
SELECT DEFAULT( id ) , DEFAULT( EXAMPLE ) FROM test LIMIT 1
With above query, it seems that you need to have atleast one record in the table as it returns no records otherwise. For current timestamp, it return a timestamp formatted string of 0s.
Sure, using the information_schema database (which stores all the information about your database structure), you can do something like:
SELECT
COLUMN_NAME,
COLUMN_DEFAULT
TABLE_NAME
FROM information_schema.COLUMNS
WHERE
TABLE_NAME='your_table_name'
AND TABLE_SCHEMA='your_database_name'
If you have a limited number of columns, you can collect them into a row using a construct like:
SELECT
id.defaultval AS id_default,
state.defaultval AS state_default,
pubdate.defaultval AS pubdate_default
FROM
(SELECT TABLE_NAME, COLUMN_DEFAULT AS defaultval FROM information_schema.COLUMNS WHERE TABLE_NAME='your_table' AND TABLE_SCHEMA='your_database' AND COLUMN_NAME='id') id
JOIN (SELECT COLUMN_DEFAULT AS defaultval FROM information_schema.COLUMNS WHERE TABLE_NAME='your_table' AND TABLE_SCHEMA='your_database' AND COLUMN_NAME='state') state ON id.TABLE_NAME = state.TABLE_NAME
JOIN (SELECT COLUMN_DEFAULT AS defaultval FROM information_schema.COLUMNS WHERE TABLE_NAME='your_table' AND TABLE_SCHEMA='your_database' AND COLUMN_NAME='pubdate') pubdate ON id.TABLE_NAME = pubdate.TABLE_NAME
Use DESCRIBE http://dev.mysql.com/doc/refman/5.0/en/describe.html
DESCRIBE sometable [somefield]
Here is php example for single field:
$resource = mysql_query("DESCRIBE sometable somefield");
$schema = mysql_fetch_assoc($resource);
$default = $schema['default'];
And here is the php example for few fields:
$resource = mysql_query("DESCRIBE sometable");
while ($schema = mysql_fetch_assoc($resource)) {
$default_list[$schema['Field']] = $schema['Default'];
}
I see no use for such a behavior and find it wrong.
It is not convenient to use. Imagine I want to enter my own state value. I'd have to delete default 22 first.
Even worse with date. Instead of setting current datetime, you are going to make me edit whole date. Why?
And for the id it is just impossible.
Why can't you just check the input fields and if empty - not to insert at all, letting database set these defaults
You just overthinked it, I believe.
Well I have a task to store "quotes" into a database (Already done this) and display them & sort them out for the most recent quotes. I'm assuming to get the "most recent", I'd need to store date/time of the submitted quote.
I am new to PHP and trying to learn, so I don't know how to exactly do this.
Here is the PHP for adding the quotes to the database. There are two columns in the table called "quotes" and "id". I'm guessing I will also need to make a column for the date too?
require('includes/connect.php');
$quote = $_POST['quote'];
$quotes = mysql_real_escape_string($quote);
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
How would I also insert the date?
use CURDATE() if you want to insert the current date
example:
$query_auto = "INSERT INTO tablename (col_name, col_date) VALUE ('DATE: Auto CURDATE()', CURDATE() )";
but if you wqant it manually then should use this:
$query_manual = "INSERT INTO tablename (col_name, col_date) VALUES ('DATE: Manual Date', '2008-07-04')";
UPDATE
CREATE TABLE auto_ins
(
`MySQL_Function` VARCHAR(30),
`DateTime` DATETIME,
`Date` DATE,
`Time` TIME,
`Year` YEAR,
`TimeStamp` TIMESTAMP
);
INSERT INTO auto_ins
(`MySQL_Function`, `DateTime`, `Date`, `Time`, `Year`, `TimeStamp`)
VALUES
(“CURDATE()”, CURDATE(), CURDATE(), CURDATE(), CURDATE(), CURDATE());
If you only want the most recent quotes, you can simply sort your result set by their id DESC assuming the id is an auto-incremented value.
Yes, you need a third column lets say most_recent (defined as date or datetime) :
mysql_query("INSERT INTO entries (quote, most_recent) VALUES('$quotes', now())")
You will need at least couple of tables who submitted the quote and the quote table itself.
create table users(id int primary key not null, username varchar(32),pwd varchar(32));
you can add any info to that table like email address and so on.
create table quotes (
id int not null ,
user_id integer,
quote_text varchar(256),
inserted_date timestamp default current_timestamp ,primary key (id));
alter table quotes add constraint fk_users foreign key(user_id) references users(id);
Otherwise feel free to modify them.
It's not about php here its about DB design in general.
Use this code:
require('includes/connect.php');
$quote = $_POST['quote'];
$quotes = now().' - '.mysql_real_escape_string($quote);
// THIS WILL ADD THE DATE AND TIME TO YOUR $quotes STRING.
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
After successful user registration my MySQL db table puts 0000-00-00 00:00:00 into lastlogin_date and lastlogout_date fields by default. type of both fields is datetime. In my php code i'm checking if user enters to the site for the first time
$lastlogin = $db->query("SELECT `lastlogin_date` FROM `users` WHERE `id`='$_SESSION[id]'");
$row = $lastlogin->fetch_array(MYSQLI_BOTH);
$lastlogin=$row['lastlogin_date'];
if(empty($lastlogin))
{ do something}
But, seems, empty doesnt work in this case. how to check if the lastlogin_date field is empty or not? if($lastlogin=='0000-00-00 00:00:00')??
0000-00-00 00:00:00 is a value. If you don't want to put any value, you should store NULL, which would make much more sense. NULL is the lack of value.
That being said, I think the best way is to select a boolean instead of your column :
-- (lastlogin_date is NULL) if you change your table structure
SELECT (lastlogin_date = '0000-00-00 00:00:00') as has_logged_in
FROM users
WHERE id = ?;
When you fetch your query, you can use $row['has_logged_in'], which is a boolean.