How can I automatically send date/time info to my database when my form is submitted? I'm making a comment box, and I have a column in my "comments" table called "created" (which I've set as a "datetime" type) where I would like date and time information to be sent so I can display it with the comments on my page.
Is this something I would have to send from my page's code, or can I set up the database in a way that it automatically stores a time stamp every time it receives new data from the form? I'm using phpMyAdmin to manage my database, in case that helps.
This is the code I have right now for sending the form's information:
<?php
if (isset($_POST['submit'])) {
$required_fields = array("author", "body");
validate_presences($required_fields);
if (empty($errors)) {
$author = mysql_prep($_POST['author']);
$body = mysql_prep($_POST['body']);
$page_name = ($_POST['page_name']);
$query = "INSERT INTO comments (";
$query .= " author, body, page_name";
$query .= ") VALUES (";
$query .= " '{$author}', '{$body}', '{$page_name}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result) {
redirect_to("new_admin.php");
} else {
// Failure
$_SESSION["message"] = "There was an error that prevented the comment from being saved.";
}
}
} else {
$author = "";
$body = "";
}
?>
Any help would be awesome, thanks!!
Would look something like this:
$query = "INSERT INTO comments (";
$query .= " author, body, page_name, date_Added";
$query .= ") VALUES (";
$query .= " '{$author}', '{$body}', '{$page_name}', NOW()";
$query .= ")";
$result = mysqli_query($connection, $query);
Also you may need to
ALTER TABLE comments ADD date_added date time;
or you could have the database populate it for you by adding a column like so:
ALTER TABLE comments ADD date_Added TIMESTAMP DEFAULT CURRENT_TIMESTAMP
In your db table definition you can set a default value for fields, including timestamp/datetime on new rows and on updates. This means you wouldn't have to change the above code (given the above scenario).
http://dev.mysql.com/doc/refman/5.1/en/timestamp-initialization.html
Related
My code is big and I can't just pull out few lines to show my problem so I am going to explain it by using imaginary code to simplify it.
Let's say I have to-do list as table and I've defined activity and time. I don't want to have duplicate rows so I created function to prevent it.
function check_date($day, $time) {
include 'db_connect.php';
$sql = "SELECT day, dan FROM todo ";
$sql .= "WHERE day = $day AND time = '{$time}'";
$result = mysqli_query($conn, $sql) or trigger_error(mysqli_error());
if(mysqli_num_rows($result) >= 1) {
$row = mysqli_fetch_assoc($result);
return 1;
} else {
return 0;
}
}
Call on function in main file:
if(check_termin_sala($day, $time)) {
$errors['busy'] = "You are busy.";
}
And query:
if(empty($errors) {
$query = "INSERT INTO todo (";
$query .= "day, time, activity";
$query .= ") VALUES (";
$query .= "'{$day}', '{$time}', '{$activity}')";
$result = mysqli_query($conn, $query);
if(!$result) {
die("Failed." . mysqli_error($conn));
}
}
Now I want update my row by changing just activity field, but fields day and time are unchanged so when I submit update I get error because exact day and time are already inserted. What should I do to exclude this check function affecting current row date and time?
I hope you will understand me. :)
I have to insert several values in a PgSQL Table using these variables
$knr = $reader->getAttribute('Nr');
$kname = $reader->getAttribute('Name');
And this insertion code:
$SQL = "";
$SQL .= "SELECT
(konzern).knr AS knr, (konzern).name AS name
FROM konzern";
$SQL .= "INSERT INTO konzern (";
$SQL .= "knr, name";
$SQL .= ") VALUES (";
$SQL .= "'".$knr."', '".$kname."'";
$SQL .= ");".PHP_EOL;
And I want to check if the table "Konzern" already have a row with the $knr and if yes it should insert into this, if not it should create a new row
$query = doQuery("select nr from konzern where knr = '".$knr."'");
$num_rows = ($query->num_rows);
if ($num_rows > 0) {
// do nothing
}
else {
$sql .= "select nextval('konzern_nr_seq')";
}
But I have some problems puting this into the right order.
Can someone complete this code?
You can do this with a single query in this way :
INSERT INTO konzern SELECT val1, val2
WHERE NOT EXISTS(
SELECT nr from konzern where knr = 'var1'
)
Implement this approach it will be more straigth forward .
And remember to use query parameters instead of concatenating the query text, to avoid SQL Injections.
Trying to create a dynamic search functionality.
Goal : allowing user to search by email (if not empty), if empty (by last name), if both are not empty, than by both, etc.
I know I can write if statement depicting every scenario and than insert SQL command based on that, question is can this be handled in a more simplified manner. Thanks for your help.
Current function set up does OR across all fields, values are coming from $_POST:
find_transaction($email,$last_name,$first_name, $transaction_id)
{
GLOBAL $connection;
$query = "SELECT * ";
$query .= "FROM transactions WHERE ";
$query .= "email='{$email}' ";
$query .= "OR last_name='{$last_name}' ";
$query .= "OR first_name='{$first_name}' ";
$query .= "OR transaction_id='{$transaction_id}' ";
$query .= "ORDER BY date DESC";
$email = mysqli_query($connection,$query);
confirm_query($email);
return $email;
}
I do this all the time, it's not too much work. Basically build your WHERE statement dynamically based off your POST variables, using a series of if statements.
For example:
$where_statement = "";
// First variable so is simpler check.
if($email != ""){
$where_statement = "WHERE email = '{$email}'";
}
// Remaining variables also check if '$where_statement' has anything in it yet.
if($last_name != ""){
if($where_statement == ""){
$where_statement = "WHERE last_name = '{$last_name}'";
}else{
$where_statement .= " OR last_name = '{$last_name}'";
}
}
// Repeat previous 'last_name' check for each remain variable.
SQL statement would change to:
$query = "SELECT * FROM transactions
$where_statement
ORDER BY date DESC";
Now, the SQL will only contain filters depending on what values are present, so someone puts in just email, it would generate:
$query = "SELECT * FROM transactions
WHERE email = 'smith#email.com'
ORDER BY date DESC";
If they put in just last name, it would generate:
$query = "SELECT * FROM transactions
WHERE last_name = 'Smith'
ORDER BY date DESC";
If they put both, would generate:
$query = "SELECT * FROM transactions
WHERE email = 'email#email.com' OR last_name = 'Smith'
ORDER BY date DESC";
Etc., etc.
You could add as many variables you wish here, and basically if the specific variable is not blank, it will add it to the "$where_statement", and depending on if there is anything in the "$where_statement" yet or not, it will decide to start with = "WHERE ", or append .= " OR" (notice the '.=' and the space before 'OR'.
Better use Data Interactive table : http://datatables.net/
It's useful and no SQL-injection :) Good luck !
How make mysql search defined just by what is written in html form, by user, and if some form box is stayed empty, mysql should ignore it. For example:
$sql = "SELECT * FROM catalog WHERE name= '".$name."' AND publisher = '".$publisher."' ";
mysql_query($sql);
This query will display all rows where name and publisher are together. Now, what if user insert just name, and left publisher box empty. The idea is that php/mysql ignore empty form box, and display every row with inserted name. But it will not do that because $publisher will be undefined, and error emerges. How to tell musql to ignore $publisher? More generally, the question is: how to generate query that make searching defined by certain criteria if they exists, and if they don't how to just ignore it?
You can build up the sql programmatically. I am assuming you have escaped the values properly.
$sql = "SELECT * FROM catalog";
$wheres = array();
if (!empty($name)) {
$wheres[] = " name = '$name'";
}
if (!empty($publisher)) {
$wheres[] = " publisher = '$publisher'";
}
if (count($wheres)) {
$sql .= " WHERE " . implode (' AND ', $wheres);
}
//RUN SQL
Also have a read through this, you are using a deprecated mysql library.
This will allow either the name or the publisher to be NULL.
<?php
$sql = "SELECT * FROM catalog WHERE (name= '".$name."' OR name IS NULL) AND (publisher = '".$publisher."' OR publisher IS NULL)";
mysql_query($sql);
Try like
$my_var = " ";
if($publisher) //if(!empty($publisher))
$my_var = " AND publisher = '".$publisher."' ";
$sql = "SELECT * FROM catalog WHERE name= '".$name."' ".$my_var;
if the publisher is empty then you need to pass the NULL value and PLZ note that it is a bad practise.It will causes many sql injection issues.Try to put validations for the things
*Here is what I am trying to acheive: *
Basically I have a form where people can submit events to our database. In the CMS I have a page which displays a record of the number of events.
*Here is what I have: *
After the button is clicked, this script is called:
if($subject_type == 'Event') {
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
$querys = $this->tep_db_query($query);
$rows = $this->tep_db_fetch_array($querys);
extract($rows); //extract rows, so you don't need to use array
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
This works fine, however I cant seem to solve the next bit
This is the Problem
As you can see, it checks the database for the current month and adds it, this is providing that the sitename and that month are there, not a site and another month.
How would I get it to add the row in IF the sitename and month are not there?
I have been manually adding the months in now so that it works, and I am sure you can agree that's a ball ache.
Cheers peeps
if you want to check if site A + Month 11 exists do a select query against it and store the number of rows returned in a variable. ( $exists = mysql_num_rows("your query here"); )
then do an if statement against the $exists variable and proceed as you wish
if($exists) {
// update
} else {
// add
}
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$eventid = 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
}
}
this is what I have for the else statement there, however it will add one to the value if its there but will not add a new entry if its isnt.. ?
I don't see exactly how your method "checks the database for the current month and adds it "; I'll just assume that the tep_db_perform() method of your class handles this somehow.
(uhk! n00bed it; rest of the post was somehow chopped off?) Since you're already hitting the database with the select with the intent of using the data if a record is found, then you could use the resultset assigned to $rows as a means of checking if a record exists with SITENAME and Month.
See below:
if($subject_type == 'Event') {
// build query to check the database for sitename, month and year.
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
// Execute Query(wrapper for $result = mysql_query I guess?)
$querys = $this->tep_db_query($query);
// Get a resultset from database. --> you could merge this into one method with $this->tep_db_query
$rows = $this->tep_db_fetch_array($querys);
if(count($rows) > 0) {
extract($rows); //extract rows, so you don't need to use array --> I try to stay away from extract() as it makes for random variables being created.
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
} else {
// insert new record into database
// updated with code to execute insert SQL query.
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$result = $this->tep_db_query($query);
}
....
}
If I've misunderstood something, please let me know, happy to work through it with you.
Hope this helps. :)