Inserting today date from form to database - php

I'm trying to insert date when form is processed but in MySQL is inserting like
0000-00-00
I don't want user to insert date.
Here is my form
<form action="upload.php" method="post" enctype="multipart/form-data">
<textarea type="text" name="text" cols="40" rows="10"></textarea><br />
<input type="hidden" name="dt"/>
<input type="submit" name="upload" id="upload" value="Изпрати" />
And this is upload.php
<?php
if (isset($_POST['upload'])) {
$text = $_POST['text'];
$dt = date('Y-m-d', strtotime($_POST['Date']));
$db = new mysqli("localhost", "*****", "", "****");
if (mysqli_connect_error()) {
printf("Connect failed: ", mysqli_connect_error());
}
mysqli_set_charset($db, "UTF8");
$query = "INSERT INTO table (text, date) VALUES (?, ?)";
$conn = $db->prepare($query);
if ($conn == TRUE) {
$conn->bind_param("si",$text, $dt );
if (!$conn->execute()) {
echo 'error insert';
} else {
header("Location: ../admin/index.php");
exit;
}
} else {
die("Error preparing Statement");
}
} else {
echo 'error';
}
?>
What can be the problem?
edit:
In mysql the row for date is type - 'date'
edit2:
I forget about NOW()... is working perfect and is so simple.

I don't want user to insert date.
Then don't make it a part of the user-submitted form. As it stands, even if it's a hidden element, users can modify it to insert whatever date value they want. You don't want the user to insert the date, but your current code requires that the user insert the date.
If you just want it to be a system-known date, you can do this entirely in the INSERT statement at the database level:
INSERT INTO table (text, date) VALUES (?, NOW())
That way the database itself generates the current date, instead of relying on whatever the user submits. At this point you can completely remove the date input from the form and remove the parameter from the PHP code that builds the database query.

if you don't want user to be insert date than handle it at server side. My answer is for handle using PHP otherwise you can also go with NOW() mysql side handling.Choice up to you :
$dt = date('Y-m-d: H:i:s');
OR you can store it in databse as timestamp:
$dt=date("Y-m-d H:i:s");
$dt= strtotime($dt);
and retrieve it at front
date("Y-m-d H:i:s",$dt)

Replace in your code:
$query = "INSERT INTO table (text, date) VALUES (?, NOW())";

Related

adding new mySQL table row with PHP doesn't work

I got a little form:
<form id="plannerform" action="save.php" method="post">
<input id="plannername" placeholder=" " type="text" autocomplete="off" name="plannername">
<input id="plannersubmit" type="submit" value="eintragen">
</form>
As you can see there is the action="save.php" and method="post" on the text-input there is name="plannername".
And thats my php:
$con = mysql_connect("myHost","myUser","myPW");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("myDB", $con);
$sql="INSERT INTO anmeldungen (FR_PM)
VALUES ('$_POST[plannername]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
The FR_PM is one column of my table. But when I press submit, not even a new row gets created. Nothing happens.
But when I call my php with "mywebsite.com/save.php" it adds a new row in my table (with no value at "FR_PM", what's pretty obvious)
What do I do wrong?
one of the things that you need to learn if you are a beginner, you should try by all means to stay away from using mysql_* function this is depreciated and its no longer supported in php. instead use mysqli_* with prepared statements, or use PDO prepared statements.
prepared statments make you code looks clean and its easy to debug.
this is you example with prepared statements.
<form id="plannerform" action="save.php" method="post">
<input id="plannername" placeholder=" " type="text" autocomplete="off" name="plannername">
<input id="plannersubmit" type="submit" value="eintragen" name="submit">
</form>
save.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submit'])) {
if (empty($_POST['plannername'])) {
die("Enter plannername");
} else {
// prepare and bind
$stmt = $conn->prepare("INSERT INTO anmeldungen (FR_PM) VALUES (?)");
$stmt->bind_param("s", $_POST['plannername']);
if ($stmt->execute()) {
echo "New records created successfully";
} else {
echo "Could not insert record";
}
$stmt->close();
}
}
?>
The reason I used prepared statements :
Prepared statements reduces parsing time as the preparation on the
query is done only once (although the statement is executed multiple
times)
Bound parameters minimize bandwidth to the server as you need send
only the parameters each time, and not the whole query
Prepared statements are very useful against SQL injections, because
parameter values, which are transmitted later using a different
protocol, need not be correctly escaped. If the original statement
template is not derived from external input, SQL injection cannot
occur.
But when I call my php with "mywebsite.com/save.php" it adds a new row
in my table (with no value at "FR_PM", what's pretty obvious)
What do I do wrong?
Well do prevent that from happening you need to check if the form was submitted before you can actual process any thing.
Note: If we want to insert any data from external sources (like user input from a form ), it is very important that the data is sanitized
and validated. always treat input from a form as if its from a very
dangerous hacker
change your insert query:
$sql="INSERT INTO anmeldungen (FR_PM) VALUES ('".$_POST["plannername"]."')";
Or
$plannername = $_POST["plannername"];
$sql="INSERT INTO anmeldungen (FR_PM) VALUES ('".$plannername."')";
Also, use "name"= and not "id"= in the HTML form.
This is usually misleading when working with forms and HTTP POST method.
you may try
$value = $_POST['plannername'];
$sql="INSERT INTO anmeldungen (FR_PM) VALUES ('{$value}')";

Put text html into database

I want import a data (from a form) in my database but i've this error :
Parse error: syntax error, unexpected ';' in /homepages/38/htdocs/index2.php on line 7
and the script is
<?php
//Connecting to sql db.
$connect = mysqli_connect("","","","");
//Sending form data to sql db.
mysqli_query($connect,"INSERT INTO posts (email, pseudo)
VALUES ('$_POST[email]', '$_POST[pseudo]')";
?>
What is the error ?
Thank you
Solution
You have not concatenated the $_POST[] variable correctly.
You have been missing the close brace for the mysqli_query opening.
It is advised to have a separate query and then to execute the mysqli_query().
Necessary Checks:
Ensure that you have given the name for the input type in the form attributes.
Have a check that whether you have called the name what you have given in the form at the PHP code while insert.
(E.g) - Input Attribute needs to be like this
<input type="email" name="email" value="" />
Like this you have to provide for all the Input types.
PHP Code
Usage of the mysqli::real_escape_string is better if you use it avoids SQL Injection.
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$email=mysqli_real_escape_string($con,$_POST['email']);
$pseudo=mysqli_real_escape_string($con,$_POST['pseudo']);
$stmt = "INSERT INTO posts (`email`, `pseudo`)VALUES('".$email."','".$pseudo."')";
$query = mysqli_query($con,$stmt);
if($query)
{
echo "Inserted Successfully";
}
else
{
// Handle Error over here.
}
?>
$email=$_POST['email'];
$pseudo=$_POST['pseudo'];
mysqli_query($connect,"INSERT INTO `posts` (`email`, `pseudo`) VALUES ('$email', '$pseudo');");
You have missed quote inside POST .Check below code
<?php
//Connecting to sql db.
$connect = mysqli_connect("","","","");
$sql ="INSERT INTO posts (email, pseudo)VALUES('".$_POST['email']."','".$_POST['pseudo']."')";
//Sending form data to sql db.
mysqli_query($connect,$sql);
?>

have truoble with $mysqli->real_escape_string [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 7 years ago.
Hey there i have searched but can not find the answer i am looking for. My form will not post to my database i started getting sql injected so i changed my code around to use $mysqli->real_escape_string but it does not seem to want to still post all i am getting is the error in the code any help would be greatly appreciated.
<form action="" method="post">
<br/>
<input type="text" name="Key" class="dap_text_box" placeholder="Enter Key"/><br/>
<br/>
<input type="text" name="Name" class="dap_text_box" placeholder="Name"/><br/>
<br/>
<input type="text" name="Email" class="dap_text_box" placeholder="Email"/><br/>
<br/>
<input type="text" name="IP_s_" class="dap_text_box" placeholder="Enter IP"/><br/>
<br/>
<input type="submit" name="submit" value="Key Activation" class="sendbutton"/> </form> <hr/> </body> </html>
<?php
if (isset($_POST['submit'])) {
$mysqli = new mysqli("localhost", "root", "rkPJNwe0cI", "key");
// Check
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Set charset for correct escaping
$mysqli->set_charset('utf8');
echo $_SERVER["REMOTE_ADDR"]; // mmm?
$key = $mysqli->real_escape_string($_POST['Key']);
$IP = $mysqli->real_escape_string($_POST['IP']);
$name = $mysqli->real_escape_string($_POST['Name']);
$email = $mysqli->real_escape_string($_POST['Email']);
$IP_s = $mysqli->real_escape_string($_POST["IP_s_"]);
// (ID, Key, Activated, IP, Banned)
$sql = "INSERT INTO keys (ID, Key, Activated, IP, Banned, Name, Email) VALUES ('$ID1', '$key', 1, '$IP', 0, '$name', '$email')";
$sql1 = "SELECT ID, Key, Activated, IP, Name, Email FROM Keys";
$sql = "UPDATE Keys set IP='$IP_s_', Name='$name', Email='$email', Activated='1' WHERE Key='$key'";
if ($mysqli->multi_query($sql) === TRUE) {
echo "Activated";
} else {
echo "Error";
}
$mysqli->close(); }
You have quite a few things wrong from what I can see. Too long for a comment.
You use multi_query() but only have one query defined in $sql. Your insert statement and select statement don't appear to be doing anything, you overwrite the insert statement before you call multi_query().
$ID1 doesn't appear to be defined anywhere for your insert statement.
Why not use prepared statements? So much easier and efficient than trying to escape each individual string.

Pushing a comment to my database on localhost

So, I'm trying to push a comment to my database (icposts, below), and I'm not getting any results. I can pull and display the comments I directly insert into the database table fine, but when I try to send a comment from the html form, it doesn't seem to work at all.
<?php
$connect=mysqli_connect("localhost","root","");
$database=mysqli_select_db("icposts");
$username=$_POST['poster'];
$title=$_POST['postTitle'];
$body=$_POST['postText'];
$date=$_POST['currentDate'];
$submit=$_POST['submit'];
if($submit)
{
$query=mysql_query("INSERT INTO 'posts'('id', 'username', 'title', 'body', 'date') VALUES ('','$username','$title','$body','$date')");
}
?>
Here's the form's html, for reference:
<form name="input" action="comments.php" method="POST">
Username: <input id = "poster" type="text" name="poster"value="Guest" /><br>
Tite: <input id = "postTitle" type="text" name="postTitle" /><br>
Comment: <br> <textarea id = "postText" name = "postText"rows="4" cols="50"></textarea>
<input id = "submit" name = "submit" type="submit" value="Submit" />
<input id = "currentDate" name = "currentDate" type = "hidden" value = "" />
</form>
I've been looking at various examples, and I don't see anything wrong with what I've got there, when I compare it to what other people have posted online.
First, you need to pass connection to $database=mysqli_select_db("icposts");.
Then you're starting to mix MySQL APIs with mysql_query. They just don't intermix.
$database=mysqli_select_db($connect,"icposts");
then you're using the wrong identifiers for your table and columns, being quotes.
Either use ticks, or remove them (quotes) and also pass connection to the query:
$query=mysqli_query($connect,"INSERT INTO `posts` (`id`, `username`, `title`, `body`, `date`)
VALUES ('','$username','$title','$body','$date')");
Also add or die(mysqli_error($connection)) to mysqli_query() to check for DB errors, which is the reason why you are not getting errors; you're not checking for them. Error reporting is another you should look into.
Example:
if (!mysqli_query($connection,"INSERT INTO `posts` (`id`, `username`, `title`, `body`, `date`)
VALUES ('','$username','$title','$body','$date')");
)
{
echo("Error description: " . mysqli_error($connection));
}
else{
echo "Success!";
}
You can also use all 4 parameters instead:
$connect=mysqli_connect("localhost", "root", "", "icposts");
You may also want to replace if($submit) with
if(isset($_POST['submit']))
You can then get rid of $submit=$_POST['submit'];. It's best to use isset().
Nota: You will need to make sure that your currentDate column allows for blank data, otherwise you will need to give it some form of value.
Another note about the "id" column. If it is an auto_increment, you can just omit it from the query.
The database will increase on its own.
Sidenote:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
In the meantime till you get into using prepared statements, change your code using:
$username = stripslashes($_POST['poster']);
$username = mysqli_real_escape_string($connection, $_POST['poster']);
and do the same for all your variables.
Here is a prepared statements primer:
<?php
$link = new mysqli('localhost', 'root', '', 'database');
if ($link->connect_errno) {
throw new Exception($link->connect_error, $link->connect_errno);
}
// Check that the expected value has been provided via a POST request
if (!isset($_POST['input1'])) {
throw new Exception('Missing POST request parameter [input1]');
}
// now prepare an INSERT statement
if (!$stmt = $link->prepare('INSERT INTO `your_table` (`name`) VALUES (?)')) {
throw new Exception($link->error, $link->errno);
}
// bind parameters
$stmt->bind_param('s', $_POST['input1']);
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
$connect=mysqli_connect("localhost","root","");
Should be (the select db can simply be removed)
$connect=mysqli_connect("localhost","root","", "icposts");
And
$query=mysql_query("INSERT INTO 'posts'('id', 'username', 'title', 'body', 'date') VALUES ('','$username','$title','$body','$date')");
Should be
$query=mysqli_query("INSERT INTO 'posts'('id', 'username', 'title', 'body', 'date') VALUES ('','$username','$title','$body','$date')", $database);
Please do keep in mind that this is a really bad aprouch, also looking at your query it seems like the id is an auto incremented column. If that's the case, you don't even have to write it in the query itself.
You might wanna look further into Parameterizing queries.
This is a nice post for that.
How can I prevent SQL injection in PHP?

php code working incorrectly and not querying database

I'm using php and a database to add books to a database.
HTML
<form method="POST" action="addbook.php">
<p>Enter Book title :<input type="text" name="bookname"></p>
<p>Enter Book Author :<input type="text" name="bookauthor"></p>
<p><input type="submit" value="addbook"></p>
</form>
PHP
$bname = $_POST['bookname'];
$bauthor = $_POST['bookauthor'];
$dbcon = mysqli_connect('localhost','root','password','bookstore') or die('asd');
$dbquery = "INSERT INTO books (title,author) VALUES ($bname,$bauthor)";
mysqli_query($dbcon,$dbquery) or die('not queryed');
echo "Your book has been added to your online library";
I'm getting the reply ' not queryed'
try putting single quotes around the values
ie
$dbquery = "INSERT INTO books (title,author) VALUES ('$bname','$bauthor')";
You should be using PDO and prepared statements in order to prevent SQL injection. The resultant PHP would be something like this:
$bname = $_POST['bookname'];
$bauthor = $_POST['bookauthor'];
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); //Fill in these variables with the correct values ('localhost' for host, for example)
$st = $dbh->prepare("INSERT INTO books (title,author) VALUES (?,?)");
$data = array($bname, $bauthor);
$st->execute($data);
You can then add logic to check if the statement executed successfully.
Also, I think you just gave us your root password?
For more information about PDO, see this tutorial.
Check the Column names in the table,whether they match with the one in the query.also check whether they are varchar itself.
I dont find any problem in the query, and also try putting
or die(mysqli_error());
and tell what exactly you can see.
If the type is varchar , you have to use single quotes around the values.
$dbquery = "INSERT INTO books (title,author) VALUES ('$bname','$bauthor')";

Categories