I am currently learning OOP, but I can't figure out how to insert date into database.
I have tried:
$time=date('now');
$time=date("timestamp");
$time=date("Y-m-d H:i:s");
$time=date("m/d/y g:i A");
When I submit I get error:
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 '2014-03-11 14:18:07'' at line 1
I can't figure this out. Before I did use:
$result = mysql_query ("INSERT INTO test (title,url,time) VALUES ('$title','$url',now())");
I tried to use now() , but it does not seem to work. :/
Update:
Insert:
public function insert($cat,$title,$article,$author,$image,$time)
{
$sql=mysql_query("INSERT INTO blog_posts(cat, title, article, time, author, image) VALUES('$cat', '$title', '$article', '$author', '$image, '$time'");
if(!$sql)
{
echo mysql_error();
}
}
proccess file:
$cat=$_POST['cat'];
$title=$_POST['title'];
$article= $_POST['article'];
$author=$_POST['author'];
$image=$_POST['image'];
$time= date( 'Y-m-d H:i:s' );
$n=new db();
$n->connect();
$n->insert($cat,$title,$article,$author,$image,$time);
You're missing a quote:
'$author', '$image, '$time'"
^^^^^
HERE
INSERT INTO blog_posts(cat, title, article, time, author, image) VALUES('$cat', '$title', '$article', '$author', '$image', '$time'"
Your parameters are also out of order.
Columns: cat, title, article, time, author, image
Values: '$cat', '$title', '$article', '$author', '$image', '$time'
Forget about the mysql_* functions.
If you want to create future-proof applications you will use PDO. This is OOP.
$db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$db->exec('SET NAMES utf8'); // Set this transfer's charset to utf-8
$title = 'here is a title';
$url = 'here is a URL';
$time= date( 'Y-m-d H:i:s' ); // I dont know what type the time column is. (date, datetime, timestamp)-> ??
$prepare = $db->prepare("INSERT INTO test (title, url, time) VALUES (:title, :url, :time)");
$prepare->bindParam(':title', $title);
$prepare->bindParam(':url', $url);
$prepare->bindParam(':time', $time);
$prepare->execute(); // Run the query, in this case, insert!
If the time column is of type date or datetime, you can use NOW() or CURDATE() like so:
$prepare = $db->prepare("INSERT INTO test (title, url, time) VALUES (:title, :url, NOW())");
theres nothing to do with objects in this code.
and the first snippet of code is bascily overwriting all over
so its left with the latest. what exactly are you trying to achieve?
could you post some more of your code?
if you wish to use mysql OBJECT oriented, use MySQLi or PDO driver.
Related
I am having an issue where it seems my insert code is wrong but i do not know how to fix it.
It keeps resorting to my page being blank with no error_log and error reporting is not working either, below is the code
<?php
$connect = mysqli_connect("localhost","dfhdfhd","dfhdfh","fhgdfh");
$url = 'url';
$banner = 'banner';
$title = 'title';
$date = 'date';
$time = 'time';
$description = 'description';
$region = 'region';
$sponsors = 'sponsors';
mysqli_query($connect,"INSERT INTO information (url, banner, title, date, time, description, region, sponsors)
VALUES ('$url', '$banner', '$title', '$date' '$time', '$description', '$region', '$sponsors')";
?>
There's a few things wrong here.
First, a missing comma after '$date' and a missing bracket for your opening $connect,
Here:
mysqli_query($connect,"INSERT INTO information (url, banner, title, date, time, description, region, sponsors)
VALUES ('$url', '$banner', '$title', '$date', '$time', '$description', '$region', '$sponsors')");
Having checked for errors, it would have told you about those errors.
Consult these following links http://php.net/manual/en/mysqli.error.php and http://php.net/manual/en/function.error-reporting.php
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements.
you should add error_reporting and show mysqli error if a query for some reason doesn't work:
<?php
error_reporting(-1);
$connect = mysqli_connect("localhost","dfhdfhd","dfhdfh","fhgdfh");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$url = 'url';
$banner = 'banner';
$title = 'title';
$date = 'date';
$time = 'time';
$description = 'description';
$region = 'region';
$sponsors = 'sponsors';
$result = mysqli_query($connect,"INSERT INTO information (url, banner, title, date, time, description, region, sponsors)
VALUES ('$url', '$banner', '$title', '$date', '$time', '$description', '$region', '$sponsors')");
if (!result)
{
echo("Error description: " . mysqli_error($connect));
}
?>
See for more information: http://www.w3schools.com/php/func_mysqli_error.asp
Also make sure that the php is not executed somewhere, where errors would be echoed but not visible because they are outside html or hidden by css.
You also forgot a comma inbetween '$data' and '$time' and closing the mysqli_query function.
I am trying to insert data into a database after the user clicks on a link from file one.php. So file two.php contains the following code:
$retrieve = "SELECT * FROM catalog WHERE id = '$_GET[id]'";
$results = mysqli_query($cnx, $retrieve);
$row = mysqli_fetch_assoc($results);
$count = mysqli_num_rows($results);
So the query above will get the information from the database using $_GET[id] as a reference.
After this is performed, I want to insert the information retrieved in a different table using this code:
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$session = session_id();
if($count > 0) {
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
The first query $retrieve is working but the second $insert is not. Do you have an idea why this is happening? PS: I know I will need to sanitize and use PDO and prepared statements, but I want to test this first and it's not working and I have no idea why. Thanks for your help
You're not executing the query:
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
it needs to use mysqli_query() with the db connection just as you did for the SELECT and make sure you started the session using session_start(); seeing you're using sessions.
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
$results_insert = mysqli_query($cnx, $insert);
basically.
Plus...
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
If that still doesn't work, then MySQL may be complaining about something, so you will need to escape your data and check for errors.
http://php.net/manual/en/mysqli.error.php
Sidenote:
Use mysqli_affected_rows() to check if the INSERT was truly successful.
http://php.net/manual/en/mysqli.affected-rows.php
Here's an example of your query in PDO if you'req planning to use PDO in future.
$sql = $pdo->prepare("INSERT INTO table2 (id, title, price, session_id) VALUES(?, ?, ?, ?");
$sql->bindParam(1, $id);
$sql->bindParam(2, $title);
$sql->bindParam(3, $price);
$sql->bindParam(4, $session_id);
$sql->execute();
That's how we are more safe.
So i recently starting learning PHP, and now im trying to get code into my database.
The data is input from the user through a form.
here is my code:
if(isset($_POST['submit'])) {
$blogtitle = $_POST['blogTitle'];
$blogcategory = $_POST['blogCategory'];
$blogcontent = $_POST['blogContent'];
// aanmaak date van de blog
$blogdate = date("d/m.Y");
// Checkt of alle velden zijn ingevuld
if (!empty($blogtitle) && !empty($blogcategory) && !empty($blogcontent)) {
//echo "je zit nu bij de query";
$addBlogQuery = mysql_query("INSERT INTO blog (blog_ID, blog_title, blog_category, blog_content, blog_date)
VALUES (NULL, $blogtitle, $blogcategory, $blogcontent, blogdate )");
if ($addBlogQuery) {
echo "blog added successfully";
}
else {
echo "something went wrong";
}
}
else {
$this->notFilledErrorAction();
}
}
For some reason it's not adding any data my database. My connection to my database is working properly, and i dont see a mistake in my query.
Does someone see an error in this code? or could help me figure out the problem?
You have a syntax error in your INSERT statement:
$addBlogQuery = mysql_query("INSERT INTO blog (blog_ID, blog_title, blog_category, blog_content, blog_date)
VALUES (NULL, $blogtitle, $blogcategory, $blogcontent, blogdate )");
You are missing a $ here------------------------^
You also need to wrap your variables in ' single quotes:
$addBlogQuery = mysql_query("INSERT INTO blog (blog_ID, blog_title, blog_category, blog_content, blog_date)
VALUES (NULL, '$blogtitle', '$blogcategory', '$blogcontent', '$blogdate' )");
Furthermore, the mysql_* API is now deprecated. Please read the big red box here. You should start using MySQLi or PDO now whilst it is still relatively easy to change.
You need to enclose strings ,date and DATETIME values with single quotes (').
And you have not enclosed in your SQL.
Please modify your SQL as:
$addBlogQuery = mysql_query("INSERT INTO blog (blog_ID, blog_title, blog_category, blog_content, blog_date)
VALUES (NULL, '$blogtitle', '$blogcategory', '$blogcontent', 'blogdate' )");
Mysql support only following date format:
YYYY-mm-dd
but your code has different format
$blogdate = date("d/m.Y");
Try the following:
$blogdate = date("Y-m-d");
And you have passed ID null, i think you have selected ID as primary key. primary key can not be null. if your ID field support auto-increment you don't need to pass anything.
$addBlogQuery = mysql_query("INSERT INTO blog (blog_title, blog_category, blog_content, blog_date)
VALUES ($blogtitle, $blogcategory, $blogcontent, blogdate )");
Hopefully it will work.
See the changes below and try again:
$blogdate = date("Y-m-d");
$addBlogQuery = mysql_query("INSERT INTO `blog` (`blog_title`, `blog_category`, `blog_content`, `blog_date`)
VALUES ('$blogtitle', '$blogcategory', '$blogcontent', '$blogdate' )");
Use more secure way , Use PDO - Stop using MYSQL_* it's deprecated
PDO escapes itself, you doesn't need to use mysql_real_escape_string
<?php
$user="root";
$pass="";
$db = new PDO('mysql:host=hostname;dbname=databasename', $user, $pass); //establish new connection
$sql ="INSERT INTO blog (blog_ID, blog_title, blog_category, blog_content, blog_date)
VALUES (NULL, ?, ?, ?, ?)";
try{
$stmt = $db->prepare($sql);
$stmt->execute(array($a, $b, $c, $d));
if($stmt->rowCount()>0){
//done
}
}catch(PDOException $e){
echo $e->getMessage();
?>
Before inserting into database you should sanitize you data to prevent SQL injection and XSS. Use this function:
function sanitize($data){
$data= htmlentities(strip_tags(trim($data)));
return $data;
}
Try following query there is no need to use php date function mysql has native support to date and time functions
INSERT INTO blog
(`title`, `category`, `content`, `date`, `id`)
VALUES
('Title here', 'category here','blog content here', NOW(), 1);
here is SQL test SQL Fiddle
$addBlogQuery = mysql_query("INSERT INTO blog (blog_title, blog_category, blog_content, blog_date) VALUES ($blogtitle, $blogcategory, $blogcontent, blogdate )");
It seems your mistake is insert the value of blog_id by NULL. blog_id column is the primary key. If you insert blog_id by NULL, then the data can't push to your database. Since blog_id is primary key, you don't need to insert blog_id manually. It will automatically inserted.
This works...
mysqli_query
($con, "
INSERT INTO myDB (id, name, mydate)
VALUES ('$id', '$name', now())
")
This doesn't work....
mysqli_query
($con, "
INSERT INTO myDB (id, name, mydate)
VALUES ('$id', '$name', date('Y-m-d H:i:s', strtotime('+5 hour')))
")
The mydate column in MySQL is of datetime format.
Any ideas why it's not working? I'm currently using now(), but I want it to show the time in my timezone, not the server's timezone.
I'd suggest storing the date in a variable first.
$date = date('Y-m-d H:i:s', strtotime('+5 hour'));
If both your MySQL and PHP servers are operating on the same time-zone and have their clocks properly synchronized, you wont have an issue.
and then execute the query like so:
mysqli_query($con, "
INSERT INTO myDB (id, name, mydate)
VALUES ('$id', '$name', '$date')
")
I hope this helps!
strtotime() is not MySQL function, its PHP function, you need to write it for being executes...
"INSERT INTO myDB (id, name, mydate)
VALUES ('$id', '$name', '".date('Y-m-d H:i:s', strtotime('+5 hour'))."'
I'm trying to put the time of a post into my database table but i can't get it to work. maybe someone here can explain what i'm doing wrong.
This is my code:
<?php
if (isset($_POST['upload_message'])) {
$message_title = $_POST['message_title'];
$message_content = $_POST['message_content'];
}
$table_name = "posts";
$add_query = "INSERT INTO $table_name (name, content, date) VALUES ('$message_title', '$message_content', 'SELECT NOW()')";
if (mysql_query($add_query)) { //executes query and error check
echo "het artikel staat in de database";
}
else { //error message
echo "fout bij het toevoegen" . "<br />" . mysql_error();
}
?>
and this is a screen shot of my db table : http://gyazo.com/17019f143eab6e5818752c33824bde29
When I run mysql_error is get the following message :
Incorrect datetime value: 'SELECT NOW()' for column 'date' at row 1
You don't have to SELECT NOW(), just NOW()
$add_query = "INSERT INTO $table_name (name, content, date)
VALUES ('$message_title', '$message_content', NOW())";
You should use prepared statements with binded parameters using mysqli_ or PDO.
NOW() is a mysql function, you don't have to "select it" just call it.
Replace the "SELECT NOW()" for just "NOW()".
INSERT INTO $table_name (name, content, date) VALUES ('$message_title', '$message_content', 'NOW()')
Or you can use CURRENT_TIMESTAMP
INSERT INTO $table_name (name, content, date) VALUES ('$message_title', '$message_content', CURRENT_TIMESTAMP);
Mysql_query is deprecated as of PHP 5.5.0.
Use PDO or Mysqli !
And secure your code, we can do injection sql.