php date does not posted in the db table - php

Hi im trying to hard code and set a date to a variable inorder to insert it in db table, but after all my efforts it always prints 0000-00-00 00:00:00. data type in the date column of the table is just datetime
following is the code i tried
$retval = '2007-04-19 12:50:00';
$str_cols = "gmid, panelID, trackerID, timestamp";
$str_values ="$gmid, $panel_id, $track, $retval";
$table = "tracktable_".$track;
$query = "INSERT INTO $table ($str_cols) VALUES ($str_values)";
can any body help on this to get the assigned date in the db table

timestamp is a keyword so it should be in apostrophe like 'timestamp'.
$query = "INSERT INTO ".$table." (`gmid`, `panelID`, `trackerID`, `timestamp') VALUES ('".$gmid."', '".$panel_id."', '".$track."', '".$retval."')";

For it to function surely. Add backticks to your $table. Also there is no single quotes in your values. Use this for sure it will work.
$query = "INSERT INTO `$table` (gmid, panelID, trackerID, timestamp) VALUES ('$gmid', '$panel_id', '$track', '$retval')";

$query = "INSERT INTO ".$table." (`gmid`, `panelID`, `trackerID`, `timestamp`) VALUES ('".$gmid."', '".$panel_id."', '".$track."', '".$retval."')";

Try
$str_cols = "gmid, panelID, trackerID, `timestamp`";
$str_values ="$gmid, $panel_id, $track, '$retval'";

Related

MySQL INSERT query does not update the DB

attent table :
id int(11) primary key
userID int (11) forigen key from users table
date date
start_time text
end_time text
approv enum default 0
my query :
$sql = "INSERT INTO attent ".
"(id,userID,date,start_time,end_time,approv) ".
"VALUES ".
"('NULL','$userid','$date','$start_time','$end_time','NULL')";
$query = mysqli_query($db,$sql);
I got config.php file that help communicate with dB. I did a few insert queries before and all of them work just fine. I can not understand where is my mistake.
Write your query as below:-
"INSERT INTO attent(`id`,`userID`,`date`,`start_time`,`end_time`,`approv`)
VALUES(NULL,'$userid','$date','$start_time','$end_time',NULL)"
Try like this use back tick,because date is reserved word in mysql
$sql = "INSERT INTO `attent` ".
"(`id`,`userID`,`date`,`start_time`,`end_time`,`approv`) ".
"VALUES ".
"('','$userid','$date','$start_time','$end_time','')";
It's easier to understand what's going on if you will try to put such a query manually through e.g. phpMyAdmin
I don't know your table structure but try to skip id attribute as it's often autoincrementable. You can always skip the fields that is not set to NOT NULL.
Like that:
$sql = "INSERT INTO `attent` ".
"(`userID`,`date`,`start_time`,`end_time`,`approv`) ".
"VALUES ".
"('$userid','$date','$start_time','$end_time','')";

INSERT INTO TABLE .. php - variable in sql query

I have php script containing following SQL query (working oK):
$query = 'INSERT INTO persons'.
'(name,
surname
)'.'VALUES
( "'.$_REQUEST["name"].'",
"'.$_REQUEST["surname"].'"
)';
Where $_REQUEST["name"] and $_REQUEST["name"] are variables passed from html form.
usin php 4.5 and MariaDB 5.5
Problem rises when i try to substitute persons by variable - eg. $table:
$table = "persons";
$query = 'INSERT INTO '.$table.''.
'(name,
surname
)'.'VALUES
( "'.$_REQUEST["name"].'",
"'.$_REQUEST["surname"].'"
)';
I have been trying different variations with double qutes/single qutes/dots :). But still struggling with this..
Thx for possible answer.
Its a simply case of knowing how the single and double quote works in PHP
Try this
$table = 'persons';
$query = "INSERT INTO $table (name,surname)
VALUES ( '{$_REQUEST['name']}',
'{$_REQUEST['surname']}' )";
Now of course you should not be using the mysql_* extension anymore but if you have to you should at least try and sanitize the input values before you use them
So the code becomes
// do at least this to sanitize the inputs
$_REQUEST['name'] = mysql_real_escape_string($_REQUEST['name']);
$_REQUEST['surname'] = mysql_real_escape_string($_REQUEST['surname']);
$query = "INSERT INTO $table (name,surname)
VALUES ( '{$_REQUEST['name']}',
'{$_REQUEST['surname']}' )";
$table_name = 'persons';
$query = "insert into ".$table_name." (name,surname) values ('".$_REQUEST['name']."','".$_REQUEST['surname']."') ";

MySQL query mishandling date field

I've got a PHP/MySQL script that is yielding strange results on a date field. All along the process, my dates are fine until the very end. The final result has every entry in the date field as '0000-00-00'. I'm totally stuck and don't know what else to do. I can tell that this is an issue with PHP not interpreting this as a date, but I don't know how to fix it. Here is my code:
$sql = "CREATE TABLE temp_workouts (my_date date, sg_id int(11), loc_id int(11))";
$result = mysql_query($sql);
if (!$result) {
$tag_success = "failure";
$tag_message = mysql_error();
echo encodeJSON($tag_success, $tag_message);
die();
}
$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$my_date = $row['my_date'];
echo $my_date . " "; //<--this output looks perfect
$sql = "INSERT INTO temp_table (my_date) VALUES ($my_date)";
$result2 = mysql_query($sql);
}
die();
When I flip over to MyPHPAdmin and look at the table, the entire column my_date contains '0000-00-00'. How can I get PHP to recognize this as a 'Y-m-d' formatted date? Thanks. I appreciate any help.
I suspect the issue is that you haven't enclosed a string literal in single quotes:
INSERT INTO temp_table (my_date) VALUES ('$my_date')
^--- ^--- string literals in single quotes
Otherwise, the statement is probably something like:
... VALUES (2013-08-22)
MySQL isn't converting that into a valid date, issuing a warning message, and inserting a "zero" date.
Your immediate problem is that you don't use quotes around date values in your insert statement.
Change
$sql = "INSERT INTO temp_table (my_date) VALUES ($my_date)";
to
$sql = "INSERT INTO temp_table (my_date) VALUES ('$my_date')";
^ ^
Now, you can just use INSERT ... SELECT syntax to achieve your goal in one go
INSERT INTO temp_table (my_date)
SELECT my_date
FROM my_table
Therefore this part of your code
$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$my_date = $row['my_date'];
echo $my_date . " "; //<--this output looks perfect
$sql = "INSERT INTO temp_table (my_date) VALUES ($my_date)";
$result2 = mysql_query($sql);
}
can be changed to
$sql = "INSERT INTO temp_table (my_date)
SELECT my_date FROM my_table";
$result2 = mysql_query($sql);
On a side note: Consider switching to either PDO or MySQLi and use prepared statements.
Try this one...This will re-convert it to date, and then save..
$dt = strtotime($row['my_date']);
$date = date("Y-m-d",$dt);
$sql = "INSERT INTO temp_table (my_date) VALUES ({$date})";

Passing NULL from PHP to MySQL for auto increment

So I have a database setup in MySQL with three columns. The first column is 'idnum' that auto increments the users id numbers. The second and third are first and last names respectfully. My problem is when I go to send the the names to the DB via a query string in my PHP file, I get a couple different errors back...
When I send the query:
$sql = "insert into namesdb values('NULL', 'firstname', 'lastname')";
$result = $db->query($sql);
I get back this error: "Incorrect integer value: 'NULL' for column 'idnum' at row 1." Because column 1 is an INT type.
But then when I send this query:
$sql = "insert into namesdb values(".NULL.", 'firstname', 'lastname')";
$result = $db->query($sql);
I get back a syntax error...
Any idea on what the heck I'm doing wrong here??
Thank you for any help!
It should be:
$sql = "insert into namesdb values(NULL, 'firstname', 'lastname')";
$result = $db->query($sql);
'NULL' is a string of "NULL".
Though another option (the one I would go with) is to list the columns explicitly:
INSERT INTO namesdb (firstname, lastname) VALUES ('firstname', 'lastname')
I prefer listing the columns because it is more future proof, and it's easier to see what's going on. Imagine if columns are rearranged, added, or removed in the future. Suddenly fixing your queries is going to be a massive pain if you have to remove the 6th unnamed parameter everywhere (for example).
Its better specify field names which you want to insert and dont specify id field
like
insert into namesdb(firstname,lastname) values('firstname', 'lastname')
It will auto increment your id field
You can write query this way to avoid that problem..
$sql = "INSERT INTO table_name SET column_name_1 = 'value_1', column_name_2 = 'value_2'";
$sql = "insert into namesdb values('NULL', 'firstname', 'lastname')";
In the above query 'NULL' is a string object and your column is an Integer so the error.
$sql = "insert into namesdb values(".NULL.", 'firstname', 'lastname')";
In this query you are sending php NULL value so the final query looks like the following
"insert into namesdb values(, 'firstname', 'lastname')";
So it is invalid.
The correct way to insert should be like this
$sql = "insert into namesdb values(NULL, 'firstname', 'lastname')";
or like this
$sql = "insert into namesdb values('firstname', 'lastname')";
The reason above query works is because of the auto increment.

How do I replace record if one variable has changed?

I am taking a calendar feed with a PHP file and I need to compare it to my database. If the $lastEdited variable is different than what is in the database, I need to change the record. I'm really new to SQL, so I'm not sure what to do. I just have Date_Edited set as a VARCHAR so I just need to compare the strings. I have this:
$query = "SELECT * FROM myTable WHERE Event_ID='$id'";
$result = mysql_query($query);
if (!mysql_num_rows($result)) {
mysql_query("INSERT INTO myTable (Event_ID, Date_added, Date_edited, Title)
VALUES ('$id', '$dateAdded', '$lastEdited', '$title')");
}
How do I compare $lastEdited to Date_edited and change the row if they are different?
you need to do something like
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if($lastEdited != $row['Date_added']){
# run update query
mysql_query("update myTable set
// here insert all update fields you need like
Date_added = '$dateAdded', Date_edited = '$lastEdited' , Title = '$title'
WHERE Event_ID='$id' ");
}
You probably want to use the UPDATE statement.

Categories