0

My page lists out all of the rows from a MySQL table and puts them inside separate divs as links.

        while($row = mysqli_fetch_array($result))
        {
            echo "<a href='projects/" . $row['dir'] . "'><div>";
            echo "<h2>" . $row['name'] . "</h2>";
            echo "<p>Created: " . $row['date_created'] . "</p>";
            echo "<p>Last opened: " . $row['date_last_opened'] . "</p>";
            echo "<p>" . $row['description'] . "</p>";
            echo "</div></a>";
        }

When I click on a box (div), it opens that specific project. What I need, is to update the 'date_last_opened' field for a project to the current date when I click into one. The column for it in the table is of type 'date'.

Thanks to anyone that can help.

7
  • Somekind of redirect to project with update row. Commented Feb 9, 2015 at 0:15
  • Does the value of date_last_opened change in your database prior to opening the project in which it's found? Commented Feb 9, 2015 at 0:15
  • 1
    can you use javascript and Jquery or you want to do only with PHP? Commented Feb 9, 2015 at 0:17
  • @noob I don't mind using JavaScript and Jquery if there is an easy work around with them. Not too great with it though. Commented Feb 9, 2015 at 0:18
  • @che-azeh No the value does not change. I manually put them into the table, so it's static at the moment. I just need it to update to the current date when the link is pressed. Commented Feb 9, 2015 at 0:19

1 Answer 1

1

Simple method would be use of Jquery and AJAX:

First add click function to your link in while loop like this:

echo "<a href='projects/" . $row['dir'] . "' onclick='update(".$row['name'].")';><div>";

and in your JS file use Jquery Ajax:

function update(name){
var now = new Date();
var dateToInsert = now.format("dd/M/yy h:mm tt");//or whatever format you need
var projectName = name;

$.ajax({
type: "POST",
url: "update.php",
data: { date: dateToInsert, name: projectName}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
}

and your update.php:

if(isset($_POST['date']) && $_POST['name']){
$sql = "update yourTable set date ='".$_POST['date']."' where name= '".$_POST['name']."'";
//Rest of the code to execute query
}
else{
    echo "AJAX call failed to send post variables";
}
Sign up to request clarification or add additional context in comments.

1 Comment

This worked great. I had an ID column in the table, so I used that instead of the 'name'. And in the SQL query, I had to format it like so: ...SET date_last_opened = '".$_POST['date']."' WHERE... And for anyone else, the date.format works using this. Many thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.