i found an old blog script (very old) kicking around on my PC. im having troubles with fetching the date and time from my DB to display in PHP. Can someone help me.
This is my MySQL DB setup.
CREATE TABLE blog_posts (
id int(11) NOT NULL auto_increment,
title varchar(30) NOT NULL default '',
news text NOT NULL,
poster varchar(15) NOT NULL default '',
date timestamp(14) NOT NULL,
PRIMARY KEY (id)
) TYPE=MyISAM;
And this is what im using to send a post:
<?php
include "db.php";
$title=$_POST['title'];
$news=$_POST['news'];
$poster=$_POST['poster'];
$query="INSERT INTO $blogposts (title, news, poster) VALUES ('$title', '$news', '$poster')";
$result=mysql_query($query) or die (mysql_error());
mysql_close();
header("Location: post.php");
?>
And finally this is what im using to call the date on the front-end:
<?php echo "posted on: - ".$day.".".$month.".".$year." at ".$hour.":".$min; ?>
I'm no expert (clearly) but the call for the date doesnt look right to me. Anyone have any ideas on how i could make it work, or even make it better??
EDIT::
<?php
include "db.php";
//query
$query="SELECT * FROM ".$blogposts." ORDER BY id DESC LIMIT 0,$limit ";
$result=mysql_query($query) or die (mysql_error());
//loop
while($row=mysql_fetch_array($result))
{
$querycomment = "SELECT ID FROM ".$newscomments." WHERE newsid=".$row['id'];
$resultcomment=mysql_query($querycomment) or die (mysql_error());
$num_rows = mysql_num_rows($resultcomment);
ereg("^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})",$row['date'],$res);
$year=$res[1];
$month=$res[2];
$day=$res[3];
$hour=$res[4];
$min=$res[5];
$sec=$res[6];
?>
Thanks
As date column has TIMESTAMP data type and got not null constraint so it will have default current_timestamp value if no data posted on date column while inserting. see mysql timestamp ref manual.
So to achieve a result that you ask you can try fetch that data by using code like this:
$sql = "select id, title, news, poster, DATE_FORMAT(date,'%d.%m.%Y at %k:%i') as posteddate from blog_posts";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
echo $row["title"]."<br/>";
echo "By : " . $row["poster"]."<br/>";
echo "posted on: - " . $row["posteddate"]."<br/>"; //"posted on: - 03.03.2011 at 7:35"
}
You don't seem to be adding any value to the date field in your insert command. You could use now() to add the current time stamp to add the current time during the insert. To extract the time you could either (a) read the date field from the table and format the time using PHP or (b) get formatted fields of the time stamp in the select command using the mysql date and time functions
You also need to have some code to read the values in your PHP to read the values for the fields. This seems to be missing in your question.
Surely you haven't defined any of the date variables, that you're trying to use?
Related
I've got following code, as seen, I have two INSERT statements, which insert two records - one with current date and the second one -1 day. The problem seems to be with a mysql_insert_id. I'm getting following error:
Duplicate entry '28' for key 'PRIMARY'
Looks like the ID remains the same for both statements and also the first "INSERT" is added without any trouble, the problem is at the line where trying to add the second record into the same table. Here's the script:
<?
include("session.php");
include("database_common.php");
if (isset($campaignName) & isset($campaignRedirect)) {
$dataTable = 'qrData_'.$_SESSION['displayName'];
$statTable = 'qrStat_'.$_SESSION['displayName'];
$query = mysql_query("INSERT INTO ".$dataTable." VALUES(".mysql_insert_id($connection).", '".$campaignRedirect."', '".$campaignName."');", $connection);
$statBlank1 = mysql_query("INSERT INTO ".$statTable." VALUES(".mysql_insert_id($connection).", CURDATE() - INTERVAL 1 DAY, 0, '".$campaignName."');", $connection);
$statBlank2 = mysql_query("INSERT INTO ".$statTable." VALUES(".mysql_insert_id($connection).", CURDATE(), 0, '".$campaignName."');", $connection);
if ($statBlank1) echo "stat 1 ok";
else echo mysql_error($connection);
if ($statBlank2) echo "stat 1 ok";
else echo mysql_error($connection);
if ($query) die("<center>Kampaň úspešne vytvorená<br><br><button onclick='parent.jQuery.fancybox.close();' name='submit' class='btn btn-primary'>Zatvoriť</button></center>");
else die("<center>Vyskytla sa chyba. Prosím, zopakujte Vašu požiadavku.</center>");
}
?>
Here's a table structure:
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date DEFAULT NULL, `usageCount` int(11) DEFAULT NULL,
`campaign` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`)
any suggestions?
Okay guys, I made it a bit amish, but it works. I'm getting last id directly from mysql and increase it by 1 in a next record like this:
$statBlank1 = mysql_query("INSERT INTO ".$statTable." VALUES(ID, CURDATE() - INTERVAL 1 DAY, 0, '".$campaignName."');");
$statBlank2 = mysql_query("INSERT INTO ".$statTable." VALUES(LAST_INSERT_ID() + 1, CURDATE(), 0, '".$campaignName."');", $connection);
ID in the first query is undefined, however table structure always changes NULL value to NOT NULL, which will be, in this case the next incremented value. Hope somebody will find this helpful.
remove parameter from mysqli_insert_id..i.e. only mysqli_insert_id is to be written.. & echo the query to be inserted..you will get the value what is being inserted..use mysqli_free_result after each insert query
Description :
I have an SQL query that inserts the data into the table (I AM USING MYSQL)
Then I have another sql query that inserts data into another table with an id of the data inserted before it... I achieved it couple of months ago using a very rookie method like this
if(mysqli_query($con,
"INSERT INTO `plumit`.`posts` (
`posted_on_id`,
`poster_id`,
`post_type` ,
`post` ,
`likes` ,
`dislikes` ,
`comments` ,
`post_date`
) VALUES (
'$posted_on_id',
'$reg_no',
'text',
'$data',
'0',
'0',
'',
'$datetime'
)")
){
$result = mysqli_query($con,
"select * from posts order by post_id desc limit 1"
);
while ($rows=mysqli_fetch_array($result,MYSQLI_BOTH))
{
$post_id = $rows[0];
}
if(mysqli_query("insert into another table using $post_id"))
{
echo "Success";
}
}
now I am changing all my code because right now I am making too much requests to the server for queries and have started to learn how to optimize the code and use smarter ways of quering the database...
In order to get the last inserted id I used mysql_insert_id() instead of using the select statement
but that returned me nothing but 0.
So after a lot of searching I found out that I have to create persistent database connections in order to make it work So I included this in my php file I am using to insert data
$cfg['PersistentConnections'] = TRUE;
but that didn't work either if you Google it there are many links that say that creating persistent connections is a very bad idea etc...
All I want is to get the id of the row I inserted not last inserted row because if I get the ID of the last inserted row it can be the id of a different row lets say while i am getting the last id some one else inserts the data so it'll get the id of that row which is wrong ... there will 1000 of users inserting the data and I want the id of the row I just inserted and I have no idea what to do now ?? Any body ?
EDIT: The plugin in question is located here.
PHP beginner here using a JQuery Star Rating snippet and have gotten it to work perfectly. My problem is that it is currently configured to count and display the average of many ratings (for public applications). I'm trying to simplify the plugin so that it allows one to set a personal rating (as if rating your own songs in iTunes). The user may update their rating, but no partial stars would ever exist. I've broken the plugin many times trying to get it working, but to no avail. The mysql database exists as follows:
CREATE TABLE IF NOT EXISTS `pd_total_vote` (
`id` int(11) NOT NULL auto_increment,
`desc` varchar(50) NOT NULL,
`counter` int(8) NOT NULL default '0',
`value` int(8) NOT NULL default '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
If I can get it working the way I imagine, I wouldn't require both the counter and value columns, simply a single INT column that holds a value between 1 and 5. Currently counter accumulates the number of votes, while value aggregates the ratings. The stars are then displayed using (value/counter)*20 (as a percentage). The PHP is below (original):
<?php
// connect to database
$dbh=mysql_connect ("localhost", "user", "pass") or die ('Cannot connect to the database');
mysql_select_db ("thenally_pd",$dbh);
if($_GET['do']=='rate'){
rate($_GET['id']);
}else if($_GET['do']=='getrate'){
// get rating
getRating($_GET['id']);
}
// get data from table
function fetchStar(){
$sql = "select * from `pd_total_vote`";
$result=#mysql_query($sql);
while($rs = #mysql_fetch_array($result,MYSQL_ASSOC)){
$arr_data[] = $rs;
}
return $arr_data;
}
// function to retrieve
function getRating($id){
$sql= "select * from `pd_total_vote` where id='".$id."' ";
$result=#mysql_query($sql);
$rs=#mysql_fetch_array($result);
// set width of star
$rating = (#round($rs[value] / $rs[counter],1)) * 20;
echo $rating;
}
// function to set rating
function rate($id){
$text = strip_tags($_GET['rating']);
$update = "update `pd_total_vote` set counter = counter + 1, value = value + ".$_GET['rating']." where id='".$id."' ";
$result = #mysql_query($update);
}
?>
Thanks for a point in the right direction,
Mike
I am unsure as I have no access to the rating system you are using yet just glancing at what you have I guess you could keep the counter set to 1 (if removing it breaks the jQuery Rating System) and have the value updated by the person so when you fetch it they only see their value (make sure value can't go above 5). That way if the value is set to 5 then it will show 5 because it isn't finding other ratings.... (based on my understanding) You will also have to add a user id so you know which persons rating to fetch (since you want it personal). This depends on how dependent the application is a specific database design.
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());
I'm looking to run a mysql_query() that allows me to create a new table within a database and name it according to the current date and time.
Example: Create a table named 2012-01-09-03-00-00, or something along those lines.
I know that this is not an optimal way of doing things, but ultimately I'm going to take the data on this table and dump it into a bigger database.
I've tried the code:
<?php
$date = date('YmdHis', time()-(3600*5));
$exportSQL = "CREATE TABLE $date(
FirstName varchar(15)
)";
mysql_select_db($database);
mysql_query($exportSQL) or die (mysql_error());
echo "Table created!";
?>
But this has been to no good. Please Help and thanks in advance.
EDIT: THIS HAS BEEN SOLVED. THE CODE WORKING SHOULD LOOK LIKE THIS:
<?php
$date = date('YmdHis', time()-(3600*5));
$exportSQL = "CREATE TABLE `$date`(
FirstName varchar(15)
)";
mysql_select_db($database);
mysql_query($exportSQL) or die (mysql_error());
echo "Table created!";
?>
Except that it is very weird design, if you want to name table in such a way - place its name in square brackets, like this:
CREATE TABLE [2012-01-09 12:20:15.010] (your columns)
that means that you should have the name of the table BEFORE composing the query, OR you have to use dynamic sql like this:
DECLARE #sql NVARCHAR(MAX)
SET #sql = N'CREATE TABLE['+
CAST(DATEPART(year, GETDATE()) AS NVARCHAR)+N'-'+
CAST(DATEPART(month, GETDATE()) AS NVARCHAR)+N'-'+
CAST(DATEPART(day, GETDATE()) AS NVARCHAR)+N'-'+
CAST(DATEPART(hour, GETDATE()) AS NVARCHAR)+N'-'+
CAST(DATEPART(minute, GETDATE()) AS NVARCHAR)+N'-'+
CAST(DATEPART(second, GETDATE()) AS NVARCHAR)+
N'] (FirstName varchar(15))'
EXEC(#sql)
The presented syntax is for sql server, so due to the sql compliance you can replace square brackets with double quotes and use proper date functions, but the approach left just the same