I am trying to insert a date from a variable into a mysql database. The format of the column is date and it has dates in the column. The dates in the column look like yyyy-mm-dd
my date variable also looks like this however it will not insert the date into the column and even i do not get an error just a white screen.
<?php
//here is the code to insert this does not work
mysql_query("INSERT INTO `invoices` (account_id, purchased_date, sales_rep, INV_ID)
VALUES ('".$acctid."', '".$date"','".$row['8']."', '".$invid."' )") or die("load1 -" . mysql_error());
<?php
//this does work but it does not have the date.
mysql_query("INSERT INTO `invoices` (account_id, sales_rep, INV_ID)
VALUES ('".$acctid."', '".$row['8']."', '".$invid."')") or die("load1 -" . mysql_error());
not sure what the problem is. I have displayed the $date variable onto the screen and it looks fine ex. 2012-06-01
so I am not sure why it can not insert this into the database.
Your error is that you have a parse error in this line:
VALUES ('".$acctid."', '".$date"','".$row['8']."', '".$invid."' )")
Your server has display_errors turned off, so you're not seeing the fatal error output.
You can fix it by adding a concatenation operator (.) like so:
VALUES ('".$acctid."', '".$date."','".$row['8']."', '".$invid."' )")
Also, in the future, I find it more readable to write my queries like so:
VALUES ('{$acctid}', '{$date}', '{$row['8']}', '{$invid}')
If you prefer not to use interpolation (that's the method of string "injection" used above), you could still use concatenation (your original method) but use spaces to make it more readable (and easier to find syntax errors before you try to execute it):
"VALUES ('" . $acctid . "', '" . $date . "' , '" . $row['8'] . "', '" . $invid . "')";
And before all the haters shun me for suggesting interpolation over concatenation, let me refer you to this tweet by #rasmus stating that interpolation is actually faster than concatenation, these days.
<?php
//here is the code to insert this does not work
mysql_query("INSERT INTO `invoices` (account_id, purchased_date, sales_rep, INV_ID) VALUES ('".$acctid."', '".$date"','".$row['8']."', '".$invid."' )") or die("load1 -" . mysql_error());
?>
the error is:
PHP Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING on line 1
There is no . after $date.
Try to use new \DateTime('yyyy-mm-dd')
<?php
//here is the code to insert this does not work
mysql_query("INSERT INTO `invoices` (account_id, purchased_date, sales_rep, INV_ID)
VALUES ('".$acctid."', '".new \DateTime('yyyy-mm-dd')."','".$row['8']."', '".$invid."' )") or die("load1 -" . mysql_error());
You can use
mysql_query("INSERT INTO `vipanda2`.`invoices` (account_id, purchased_date, sales_rep, INV_ID)
VALUES ('".$acctid."', '".date('Y-m-d',mktime(0, 0, 0, date("m", $date), date("d", $date), date("Y", $date)))."','".$row['8']."', '".$invid."' )") or die("load1 -" . mysql_error());
Related
I am new to all this MySQLi, and I can't seem to find any useful information that works for me.. I've tried the following code, but to no avail:
if(isset($_GET['submit']))
{
$stamp = date("D M d, Y G:i a");
$mysqli->query("INSERT INTO down (timestamp, username) VALUES ('" . $stamp . "', '" . USER_NAME . "')");
}
I am unaware as to what I'm doing wrong, so maybe some insight? Or it would be great if someone could reference me to some websites? Hence nothing seems to work for me!
HTML is:
<form method="post">
<b>Submit a downtime report*</b>: <input type="submit" name="submit" value="Report">
</form>
You don't have to use date() function in PHP. You can use NOW() or CURRENT_TIMESTAMP() in MySQL
$mysqli->query("INSERT INTO down (`timestamp`, `username`) VALUES (NOW(), '" . USER_NAME . "')");
More date functions you can find here
I guess USER_NAME is a constant and it's set.
As for useful resources, have you tried the official documentation ?
http://php.net/manual/en/book.mysqli.php
It seems to be pretty comprehensive.
Change this to
$mysqli->query("INSERT INTO down (timestamp, username) VALUES ('" . $stamp . "', '" . USER_NAME . "')");
to
$mysqli->query("INSERT INTO down (`timestamp`, `username`) VALUES ('" . $stamp . "', '" . USER_NAME . "')");
Reason: timestamp is also a type in SQL hence you should use it like that.
"timestamp" is a MySQL keyword and so is interpreted as a data type rather than a column name and then the syntax doesn't make any sense. You can solve this by escaping the column name using back ticks. This is a good practice for all table and column names by the way, regardless of whether they are keywords or not. So changing the query as follows should work:
$mysqli->query("INSERT INTO `down` (`timestamp`, `username`) VALUES ('" . $stamp . "', '" . USER_NAME . "')");
I have made a sql row as type: datetime.
The input for datetime should be like: 2013-02-02 10:13:20
You get the drill like: 0000-00-00 00:00:00
Now In php I use date("Y-m-d H:i:s");(current date and time) to insert it into my database. There are other variables as well. Those variables get inserted,but the datetime row stays: 0000-00-00 00:00:00
I first got this code when everything except the date worked:
$resultaat = $mysqli2->query("INSERT INTO questions (title, description, username, date_made) VALUES ('" . $title . "','" . $description . "', '".$username ."','".date("Y-m-d H:i:s")."')");
but all the information in the databases will get "" around them.(Which could have caused the date to jump to 0000-00-00 00:00:00
Now when I try to insert again with other information, it wont even insert anymore. My problems:
What is the real problem for the date to set to 0000-00-00 00:00:00? Is it the automatic ""?
If it is the "", how can I lose them?
EDIT:
Nvm I lost the "" It wasn't the problem that cause the insert to fail at the second try.
- Why wont it insert in it anymore after I inserted once?
Now these aren't really different questions because it's about the same problem but here's my code and yes I know SQL Injection, I'll fix it later:
if (isset($_POST['title'])) {
$alles_goed=true;
$description=$_POST['description'];
$title=$_POST['title'];
$username=$_SESSION['username'];
if ($title=''){
$alles_goed=false;
echo'title is empty';
}
if($alles_goed==true){
$resultaat = $mysqli2->query("INSERT INTO questions (title, description, username, date_made) VALUES ('" . $title . "','" . $description . "', '".$username ."','".date("Y-m-d H:i:s")."')");
}
}
Try this:
$a=date("Y-m-d H:i:s");
if (!$resultaat = $mysqli2->query("INSERT INTO questions (title, description, username, date_made) VALUES ('$title','$description','$username','$a')"))
{
printf("Errormessage: %s\n", $mysqli2->error);
exit;
}
and check if there is any error produced.
As to why is inserting it only once, you might have unique field.
Just use a now() on MySQL
$resultaat = $mysqli2->query("INSERT INTO questions (title, description, username, date_made) VALUES ('" . $title . "','" . $description . "', '".$username ."',now()");
I'm new to php and I have a problem. I'm working on a webpage to receive gps coordinates from an android app. I'm getting an error about an SQL statement here is the code:
?php
ini_set('display_errors',1);
error_reporting(E_ALL);
date_default_timezone_set('America/New_York');
$script_tz = date_default_timezone_get();
if (strcmp($script_tz, ini_get('date.timezone'))){
echo 'Script timezone differs from ini-set timezone.';
} else {
echo 'Script timezone and ini-set timezone match.';
}
$usr = "bikemap";
$pwd = "pedalhard";
$db = "test";
$host = "localhost";
$cid = mysql_connect($host,$usr,$pwd);
if (!$cid) { echo("ERROR: " . mysql_error() . "\n"); }
$userID = $_POST['userID'];
$date = $_POST['date'];
$time = $_POST['time'];
$lat = $_POST['lat'];
$long = $_POST['long'];
$alt = $_POST['alt'];
mysql_select_db("test");
$SQL = " INSERT INTO gpsdata ";
$SQL = $SQL . " (userID, date, time, lat, long, alt) VALUES ";
$SQL = $SQL . " ('$userID', '$date', '$time', '$lat','$long','$alt') ";
$result = mysql_query("$SQL");
if (!$result) {
echo("ERROR: " . mysql_error() . "\n$SQL\n"); }
mysql_close($cid);
?>
Here is the error I recieved:
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 'long, alt) VALUES ('', '', '', '','','')' at line 1 INSERT INTO
gpsdata (userID, date, time, lat, long, alt) VALUES ('', '', '',
'','','')
LONG is a reserved word in mySQL.
Either wrap the field name in backticks:
$SQL = $SQL . " (`userID`, `date`, `time`, `lat`, `long`, `alt`) VALUES ";
or rename the field.
Also, your script is vulnerable to SQL injection. You want to fix that before going live.
long is being parsed as a datatype, not a field name.
To fix this, put quotes around field names, as in:
$SQL = $SQL . " (`userID`, `date`, `time`, `lat`, `long`, `alt`) VALUES ";
long is a reserved word in MySQL. Use lon, or quote it using ` characters.
LONG is a reserved word in my SQL, you need to enclose it with backticks
mysql_query("INSERT INTO contact_forms(name,ts,ip,email,option,msg)
VALUES('".$name."',
NOW(),
'".$_SERVER['REMOTE_ADDR']."',
'".$email."',
'".$option."',
'".$message."')");
For some reason this thing doesn't work. It throws no errors but it just doesn't work. Can someone tell me why?
Assuming you are doing this in PHP, which is what it appears to be, try changing your code to this to see if you get an error that might be able to add a little more information:
mysql_query("INSERT INTO contact_forms(name,ts,ip,email,option,msg)
VALUES('".$name."',
NOW(),
'".$_SERVER['REMOTE_ADDR']."',
'".$email."',
'".$option."',
'".$message."')", $link);
echo mysql_errno($link) . ": " . mysql_error($link) . "<br>";
In this example the variable $link is your database connection string.
See http://php.net/manual/en/function.mysql-error.php for more information on usage.
Put mysql_error() as zerkms suggested.
Update
option is a MySQL [link=http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html]reserved word[/link] and you can not use it unless you enclose it with back tick (`).
mysql_query("INSERT INTO contact_forms(name,ts,ip,email,`option`,msg)
VALUES('".$name."',
NOW(),
'".$_SERVER['REMOTE_ADDR']."',
'".$email."',
'".$option."',
'".$message."')");
Always use mysql_error() to debug query issues. It is not a good practice to use reserve words in database schema.
Try
$date = now();
$ip = $_SERVER['REMOTE_ADDR'];
$query = "INSERT INTO contact_forms (name,ts,ip,email,option,msg)
VALUES('$name',
'$date',
'$ip',
'$email',
'$option',
'$message')";
This is my code:
function function() {
$isbn = $_REQUEST["isbn"];
$price = $_REQUEST["price"];
$cond = $_REQUEST["cond"];
$con = mysql_connect("localhost","my_usernam", "password");
if (!$con) die('Could not connect:' . mysql_error());
mysql_select_db("my_database",$con);
$sql="INSERT INTO 'Books' (isbn, price, condition)
VALUES ('$isbn','$price','$cond')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
return "It works";
But when run it results in:
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 ''Books' (isbn, price....
Anyone know why this is happening?
You should use backticks instead of single quotes for table and field names:
$sql="INSERT INTO `Books` (`isbn`, `price`, `condition`)
VALUES ('$isbn','$price','$cond')";
will work.
ps. to prevent all kinds of nasty security holes, escape the input fields with:
$isbn = mysql_real_escape_string($_REQUEST["isbn"]);
// etc etc for all fields
Wrap table names in backticks, not quotes, and make sure to escape your input for security:
$sql="INSERT INTO `Books` (`isbn`, `price`, `condition`)
VALUES ('" . mysql_real_escape_string($isbn) . "',
'" . mysql_real_escape_string($price) . "',
'" . mysql_real_escape_string($cond) . "')";