Updating database field in PHP when link is pressed - php

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.

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";
}

Related

Ajax, retrieving ID of insert from within function

I'm trying to use Ajax to insert form data into the database and return the ID of that insertion.
It currently works as far as inserting (I can see it in the database) but I'm using alert to test that it's getting the ID of the insert and it simply says undefined.
Is there something I'm doing wrong to retrieve the ID?
<script type="text/javascript">
$(document).ready(function(){
$("#submitForm").click(function(){
var string = $('#pageForm').serialize();
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "addPage.php",
data: string,
cache: false,
success: function(result){
alert(result.id);//this will alert you the last_id
}
});
});
});
</script>
addPage.php
$title = $_POST['addTitle'];
$page_type = $_POST['pageType'];
$display_id = $_POST['displayId'];
$duration = $_POST['durationSet'];
$addpage = "
INSERT INTO pages (title, page_type_id, display_id, duration)
VALUES ('$title','$page_type','$display_id','$duration');
";
if ($mysqlConn->query($addpage) === TRUE) {
$last_id = $mysqlConn->insert_id;
echo json_encode(['id'=>$last_id]);
echo "New record created successfully" . $last_id;
} else {
echo "Error: " . $addpage . "<br>" . $mysqlConn->error;
}
Try to return last inserted data id
$title = $_POST['addTitle'];
$page_type = $_POST['pageType'];
$display_id = $_POST['displayId'];
$duration = $_POST['durationSet'];
$addpage = "
INSERT INTO pages (title, page_type_id, display_id, duration)
VALUES ('$title','$page_type','$display_id','$duration');
";
if ($mysqlConn->query($addpage) === TRUE) {
$last_id = $mysqlConn->insert_id;
$data = json_encode(['id'=>$last_id]);
echo "New record created successfully" . $data ;
} else {
echo "Error: " . $addpage . "<br>" . $mysqlConn->error;
}
https://www.w3schools.com/PHP/php_mysql_insert_lastid.asp
Please first search before ask a question
if ($mysqlConn->query($addpage) === TRUE) {
$last_id = $mysqlConn->insert_id;
echo "New record created successfully" . $last_id;
} else {
echo "Error: " . $addpage . "<br>" . $mysqlConn->error;
}

Ajax - Sending and Receiving

I have 2 files, A .js and a .php. The .php connects to the MySQL DB and the .js is the front end of the system.
I'm in the middle of trying to set it up so it sends a hash key to the ajax which returns the correct data for the related person from the database.
So far it does work as it send the hash from the URL to the PHP file and returns back the data in the console log.
//AJAX Function
//Grabs Varibles from PHP
var hash = window.location.hash.substr(1);
$(function() {
$('.hashfield').text(hash)
});
$.ajax({
type: "POST",
async: false,
cache: false,
url: "SelectFromSQL.php",
//Sending URL password
data:{ hash: hash, WorkingHash : "yes" },
success: function(data){
//Return of AJAX Data
console.log(data);
},
error:function() {
console.log("FAIL");
}
})
This is within the .js file which sends the hash
<?php
if(isset($_REQUEST['WorkingHash'])){
$hash = $_POST['hash'];
function IDHASH($hash){
echo $hash;
}
IDHASH($hash);
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ID, CustomerName, ContactName, Address, City, PostalCode, Country FROM customers WHERE ID=$hash";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["ID"] . "<br>";
echo $row["CustomerName"] . "<br>";
echo $row["ContactName"] . "<br>";
echo $row["Address"] . "<br>";
echo $row["City"] . "<br>";
echo $row["PostalCode"] . "<br>";
echo $row["Country"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
This is the .php file. I need to return the data from the database related to the correct customer ID.
All the data being echoed from the while loop will need it's own variably within a js format
My Goal is to retrieve each entry from the database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["ID"] . "<br>";
echo $row["CustomerName"] . "<br>";
echo $row["ContactName"] . "<br>";
echo $row["Address"] . "<br>";
echo $row["City"] . "<br>";
echo $row["PostalCode"] . "<br>";
echo $row["Country"] . "<br>";
}
}
instead use
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
print_r(json_encode($row));
}
and in js
javacript
$.ajax({
type: "POST",
async: false,
cache: false,
url: "SelectFromSQL.php",
//Sending URL password
data:{ hash: hash, WorkingHash : "yes" },
success: function(data){
//Return of AJAX Data
data = JSON.parse(data);
console.log(data);
//YOU CAN USE data.ID , data.CustomerName and so on
},
error:function() {
console.log("FAIL");
}
})
How about something like this:
Edit
instead of return data echo it like this:
if ($result->num_rows > 0) {
// echo the data instead of return
echo json_encode($result->fetch_assoc());
}
To access the properties of the object you can in your success function do that :
success: function(data){
// parse your data first
data = JSON.parse(data);
//Return of AJAX Data
console.log(data.CustomerName);
console.log(data.ContactName);
// you can assign them to a variables if you want
var customerName = data.CustomerName;
var ccontactName = data.CustomerName;
}

Error with PHP validation

I am creating a basic auction site and got quite far with help from this community. I am near finishing this now but having a slight issue with server side validation.
Auctions are listed on a PHP page with html and PHP, PHP runs a MySQL query and then lists the results. Example here:
$result = mysqli_query($con,"SELECT * From auction WHERE category = 'Bathroom' ORDER BY ID DESC");
while($row = mysqli_fetch_array($result))
{
echo "<form name='auction' id='auction" . $row['ID'] . "'>
<input type='hidden' name='id' value='" . $row['ID'] . "' />
<div class='auction-thumb'>
<div class='auction-name'>" . $row['Item'] . "</div>";
echo "<img class='auction' src='" . $row['ImagePath'] . "' />";
echo "<div class='auction-bid'>Current Bid: £<div class='nospace' id='" . $row['ID'] . "'>" . $row['CurrentBid'] . "</div></div>";
echo "<div class='auction-bid'>Your Name: <input type='text' class='bidder' name='bidname' autocomplete='off'/></div>";
echo "<div class='auction-bid'>Your Bid: <input type='text' class='auction-text' name='bid' autocomplete='off'/></div>";
echo "<div class='auction-bid'><input type='submit' name='submit' value='Place Bid!' /></div>";
echo "<div class='bid-success' id='bid" . $row['ID'] . "'>Bid placed!</div>";
echo "</div></form>";
}
echo "</table>";
mysqli_close($con);
Once the user clicks the submit button, the following jQuery is executed:
$(document).ready(function(){
$('form[name="auction"]').submit(function(){
var id = $(this).find('input[name="id"]').val();
var bidname = $(this).find('input[name="bidname"]').val();
var bid = $(this).find('input[name="bid"]').val();
var currentbid = $('#'+id).text();
var itemdesc = $(this).find('.auction-name').text();
bid = parseFloat(parseFloat(bid).toFixed(2));
currentbid = parseFloat(parseFloat(currentbid).toFixed(2));
if (bidname == '')
{
alert("No name!")
return false;
}
/* if (bid > currentbid)
{
alert("Bid is greater than current bid");
}
else
{
alert("Bid is too low!");
return false;
}*/
$.ajax({
type: "POST",
url: "auction-handler.php",
dataType: "json",
data: {bidname: bidname, bid: bid, id: id, itemdesc: itemdesc},
success: function(data){
$('#bid'+id).fadeIn('slow', function () {
$(this).delay(1500).fadeOut('slow');
});
//$('#auction' + id).find('.nospace').html(currentbid);
},
error: function() {
alert("bid too low");
}
});
return false;
});
});
If the code POSTS, the following PHP code is run on the handler page:
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$bidname = $_POST['bidname'];
$bid = $_POST['bid'];
$id = $_POST['id'];
$itemdesc = $_POST['itemdesc'];
$highestbid = mysqli_fetch_row(mysqli_query($con,"SELECT CurrentBid from Auction WHERE ID = '$id'"));
if ($bid <= $highestbid)
{
$_SESSION['errors']['bid'] = 'Sorry, but the bid is too low';
echo json_encode($_SESSION['errors']);
exit;
}
else
{
$query = "UPDATE auction SET CurrentBid = '$bid', Bidder = '$bidname' WHERE ID = '$id'";
$query2 = "INSERT INTO auction_log (Item, Bid, Bidder) VALUES ('$itemdesc','$bid','$bidname')";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_query($con, $query2) or die(mysqli_error());
mysqli_close($con);
I added some server side validation to make sure that the bid posted is higher than what is currently in the MySQL table.
The problem I am having is that I get the "Sorry, but the bid is too low" error no matter what bid I put in.
If I put a bid higher than the current bid, I get the error, if I put a bid in lower, I get the error.
Both ways I go about it also trigger the success section of the AJAX.
I feel like I'm missing something very simple, so if anyone could help that would be great.
I am not sure why it's being downvoted, I am just looking for some help.
Thanks
The way that you're handling AJAX error is not very good because it only alerts you that you have an error, but you don't know what goes wrong.
In the AJAX object, replace the current error callback with one that logs the actual error to the console:
replace
error: function() {
alert("bid too low");
}
with
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
and you'll know for sure what is the error

AJAX only responds to the first row of php mysqli data. The other rows doesn't respond and retrieve data.

Basically, this code gets info from id.php by studentid and returns address, document cost, etc The code is returned when the button student id is clicked but only for the first row. The second row does not return any data and i cant seem to figure out the problem. please help.
<div id="briefinfo" style="display:inline-block;text-align:center;margin-left:20px;">
<?php require_once("db.php");
if ($result = $mysqli->query("SELECT * FROM requests WHERE status = 1 ORDER BY id"))
{
if ($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
echo "<div id='thumbnail'>";
echo " ". $row->lastname;
echo " ". $row->firstname;
echo "</div>";
echo "document id:" . $row->id;
echo "<br>";
echo "requested: " . $row->document;
echo "<br>";
if ($row->paidstatus == 1){
echo "payment status: paid";
}
else{
echo "payment status: not paid";
}
echo "<br>";
echo "<input type='button' value='$row->student_id' id='studentid'/>";
/*echo "<td>" . $row->document . "</td>";
echo "<td><a href='records.php?id=" . $row->id . "'>Edit</a></td>";
echo "<td><a href='delete.php?id=" . $row->id . "'>Delete</a></td>";
echo "<td><a href='unverify.php?id=" . $row->id . "'>unverify</a></td>";
echo "<td><a href='comments.php?id=" . $row->id . "'>comment</a></td>";
echo "<td>" . $row->paymentamount . " pesos";"</td>";
echo "<td><a href='paymentamount.php?id=" . $row->id . "'>set amount</a></td>";*/
}
}
else
{
echo "No results to display!";
}
}
else
{
echo "Error: " . $mysqli->error;
} ?>
</div>
This is the JS
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
//in your Javascript, put
$(document).ready ( function () {
$("#studentid").click (function(){
var studentid = $(this).val();
$.ajax({
type: 'POST',
url: 'id.php',
data: {
id: studentid
},
success: function(response) {
$("#moredata").html(response);
}
});
});
});
</script>
this id.php
<?php
// connect to the database
include('connect-db.php');
// confirm that the 'id' variable has been set
require_once("db.php");
$id = $_POST['id'];
if ($result = $mysqli->query("SELECT * FROM requests WHERE student_id=$id"))
{
if ($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
echo $row->paymentamount . " pesos";
echo "<br>";
echo $row->address;
echo "<br>";
echo $row->address2;
echo "<br>";
echo $row->country;
}
}
else
{
echo "No results to display!";
}
}
else
{
echo "Error: " . $mysqli->error;
}
?>
First row of input button shows more data in when clicked the button. Second row does not display anything anymore. help
For following statement in while loop you should use class instead of id. You should not use same ID for multiple element.
echo "<input type='button' value='$row->student_id' class='studentid'/>";
And in your jquery script you should call it this way:
<script>
//in your Javascript, put
$(document).ready ( function () {
$(".studentid").click (function(){
var studentid = $(this).val();
$.ajax({
type: 'POST',
url: 'id.php',
data: {
id: studentid
},
success: function(response) {
$("#moredata").html(response);
}
});
});
});
</script>

Get response text back from php after ajax request

I want to add data to my database, and get back the response from php which accesses the database.
javascript code:
var request = $.ajax({
type: "POST",
url: "nieuwDuel.php",
data: dataString,
success: function(response)
{
var responseText = "onbekend";
responseText = jQuery(response);
document.getElementById("duelToegevoegd").innerHTML=responseText;
$( "#openstaandeDuels" ).load( "getOpenstaandeDuels.php" );
}
});
So when the a name isn't valid or is already in existence, I can add this message to a span element in my html.
This is my php code:
<?php
if($_POST)
{
// Create connection
$con=mysqli_connect("localhost","root","root","websitedb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = getdate();
$date_time = $date['year'] . "-" . $date['mon'] . "-" . $date['mday'] . " " . $date['hours'] . ":" . $date['minutes'] . ":" . $date['seconds'];
$uitdagerArray = mysqli_query($con,"SELECT id FROM deelnemers WHERE naam='" . $_POST['uitdager'] . "'");
$uitgedaagdeArray = mysqli_query($con,"SELECT id FROM deelnemers WHERE naam='" . $_POST['uitgedaagde'] . "'");
$uitdager = mysqli_fetch_array($uitdagerArray);
$uitgedaagde = mysqli_fetch_array($uitgedaagdeArray);
$uitdagerId = $uitdager['id'];
$uitgedaagdeId = $uitgedaagde['id'];
$sql="INSERT INTO duels (uitdager, uitgedaagde, aanmaakdatum, gespeeld) VALUES ('" . $uitdagerId . "','" . $uitgedaagdeId . "','" . $date_time . "','" . "0" . "')";
if(!mysqli_query($con,$sql)) {
echo mysql_errno() . ": " . mysql_error() . "\n";
}
else {
echo "Duel Toegevoegd";
}
mysqli_close($con);
}
?>
So is it possible that the text from echo in my php code will be passed to the 'response' from the succes function?
edit:
this is my html code
<div id="nieuwDuel">
<h2>Nieuw Duel</h2>
<form name="form" method="post">
Uitdager: <input type="text" id="naamUitdager" placeholder="naam uitdager">
Uitgedaagde: <input type="text" id="naamUitgedaagde" placeholder="naam uitgedaagde">
<input type="submit" class="nieuwDuelToevoegen">
</form>
<span id="duelToegevoegd" style="display:none"></span>
Home
</div>
I assume that your PHP code is right. then what you need to change is your jQuery code.
just change the following code :
responseText = jQuery(response);
document.getElementById("duelToegevoegd").innerHTML=responseText;
into following :
responseText = response;
$('#duelToegevoegd').html(responseText);
I don't know what you are going to do with
$( "#openstaandeDuels" ).load( "getOpenstaandeDuels.php" );
So, I leave it out for now
hope it helps
Yes it should work. Try changing your JS to
var request = $.ajax({
type: "POST",
url: "nieuwDuel.php",
data: dataString,
success: function(response)
{
console.log(response);//This will output the response you are getting to the console so you can check it
$("#duelToegevoegd").html(response);
$( "#openstaandeDuels" ).load( "getOpenstaandeDuels.php" );
}
});
Also I wouldn't echo out any errors you get back to the client
echo "Failed to connect to MySQL: " . mysqli_connect_error();
Although it depends who the user is, but you don't want anyone unauthorised to see these errors

Categories