Error with PHP validation - php

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

Related

Can't get Post value ID from row table to PHP using Jquery

I know that my question may be duplicate, but I've looked through a ton of questions with the same problem, but none of the solutions worked for me.
It's pretty simple, get the item-id value and POST it to del.php.
I can't get the POST value in the php after the click.
<?php
include '../include/db.php';
$result = $mysqli->query("SELECT * FROM usuario WHERE nivel = '1'");
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td class='item-id'>" . $row['id'] . "</td>";
echo "<td>" . $row['nome']. "</td>";
echo "<td>" . $row['email']. "</td>";
echo "</tr>";
}
?>
<script type="text/javascript">
$("tr").click(function() {
var id = $(this).find('.item-id').text();
$.post('del.php',{id: id},function(json){
window.location.href = "http://localhost/unesc/3/admin/del.php";
}, "json")
});
</script>
del.php
<?php
if (isset($_POST['id'])){
$id = $_POST['id'];
echo $id;
} else {
echo "erro";
}
?>
The del.php just get the $_post['id'] and echo it.
The window.location is there so i won't have to enter the address manually.
The trigger may not be necessarily a Click, it can be a Button, woks just fine for me too.
EDIT: got the POST running with $.ajax, but now, with firebug i noticed that the post in del.php keeps returning empty.
EDIT2: got the del.php post response, but as an error, it says that 'id' don't exist.
If THIS is what you need here is the code of both pages I used
del2.php
<script type="text/javascript" language="javascript" src="jquery.min.js"></script>
<?php
//include '../include/db.php';
include 'includeconnect.php';
//$result = $mysqli->query("SELECT * FROM usuario WHERE nivel = '1'");
$result = mysql_query("SELECT * FROM usuario WHERE nivel = '1'");
while($row = mysql_fetch_array($result))
{
echo "
<table border='1'>
<tr>";
echo "<td class='item-id'>" . $row['id'] . "</td>";
echo "<td>" . $row['nome']. "</td>";
echo "<td>" . $row['email']. "</td>";
echo "</tr>
</table>
</br>";
}
echo"<div id='show_responce'>I am a text on page del2.php and I am pretty much useless apart from showing you where the responce will display</div>"
?>
<script type="text/javascript">
$("tr").click(function() {
var rep = $("#show_responce");
var id = $(this).find('.item-id').text();
var dataString = 'id=' + id;
$.ajax({
type: 'post',
url: 'del.php',
data: dataString,
success: function(html) {
rep.empty().append(html);
rep.fadeIn("slow")
}
});
});
</script>
Here is your modified del.php
<?php
if (isset($_POST['id'])){
$id = $_POST['id'];
echo "I am coming from del.php and the ID you clicked on is $id";
} else {
echo "error";
}
?>
By the way because of my account's low reputation I could not ask you what was you trying to do with this window.location but whatever. Instead of what you asked for which was basically to make sure that del.php gets the value of id as you will see I displayed it on del2.php which is the page I am making the request from.
$( "table > td" ).find( ".item-id" ).val();
or
<?php
while($row = mysqli_fetch_array($result))
{
echo "<tr id='row'>";
echo "<td class='item-id'>" . $row['id'] . "</td>";
echo "<td>" . $row['nome']. "</td>";
echo "<td>" . $row['email']. "</td>";
echo "</tr>";
}
?>
<script>
var id = [];
var values = [];
$("#row > .item-id").each(function(index){
id.push($(this).attr("id")); // [a,b,c,....]
values.push($(this).text()); //[ Dummy1, Dummy2, Dummy3, Dummy4,..]
});
</script>
Possible errors:
}, "json") here last argument means, that function expects you return valid JSON string from del.php file.
After window.localtion.href you can't access previous data, because it redirects to another page, and thus you loose all your previous data.

Refresh page / result after Ajax call

So I have a php file printing out result in a table from my database and when i mark a result using checkbox, it sends this variable to a new page deleting it. The problem is, in the same page as he Jquery code is in, all the result is displayed, and I want the result to be updated after something is deleted. Tried using window.location.reload(true); in the Ajax code, but now it only delete one result at the time. Some way to relode the page or refresh the result?
In my sakerselect.php: here it print out all result in my database containg checkbox:
$sql = "SELECT * FROM WHERE Kundenr LIKE '".$_GET['kundenr'] ."'ORDER BY CAST(Status as varchar) DESC ";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt == false){
die( print_r(sqlsrv_errors(), tue) );
}
echo "<table id='div2' border='1'>";
echo "<tr><th></th><th>Saksnr</th><th>Saksinfo</th><th>Eier</th> <th>Status</th></tr>";
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_BOTH))
{
echo "<tr>";
echo "<td><input type='checkbox' name='id[]' class='toedit' value='" . $row[0] . "'></td>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>" . $row[4] . "</td>";
echo "</tr>";
}
sakerselect is included in my KundeDisplay.php page.
KundeDisplay.php is also containing this ajax code sending the marked values to sakerdelete.php:
<script type="text/javascript">
$('#deletesaker').on('click', function () {
var ids = [];
$(".toedit").each(function () {
if ($(this).is(":checked")) {
ids.push($(this).val());
}
});
if (ids.length) {
$.ajax({
type: 'POST',
url: "php/sakdelete.php",
data: {
id: ids
},
success: function (data) {
alert(data);
$("p").text(data);
window.location.reload(true);
}
});
} else {
alert("Please select items.");
}
});
</script>
In my sakdelete.php file:
include 'connect-database.php';
foreach ($_POST['id'] as $id) {
$sql = "DELETE FROM Saker Where Saksnr = $id";
$stmt = sqlsrv_query( $conn, $sql);
if ($stmt == false) {
die( print_r(sqlsrv_errors(), true) );
}
}
you can delete one record at a time by this method
If You want to delete two are more record at a time
try this ....
http://www.codexworld.com/delete-multiple-records-from-mysql-in-php/

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>

Live update MySQL Data

I have the following code and it works great, I just want to convert it to live so it updates every 10 seconds or so without a page refresh, I'm guessing I'll need to use AJAX or Jquery but I lack the knowledge on how to do so.
=====VIA <?php include("database.php"); ?>====
<?php
// Create connection
$con=mysqli_connect("ip/host","user","pass","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
====ON THE PAGE====
<? php
$result = mysqli_query($con, "SELECT * FROM sql347511.1 ORDER BY ID DESC LIMIT 1;");
while ($row = mysqli_fetch_array($result)) {
echo "<div class='infobox_data'>Temperature: ".$row['TEMP']."°C</div>";
echo "<div class='infobox_data'>Humidity: ".$row['HUMID']."%</div>";
echo "<div class='infobox_time'>Captured: ".date("g:i:s a F j, Y ", strtotime($row["TIME"]))."</div>";
}
mysqli_close($con); ?>
Got it working, thanks for the help everyone.
Javascript
$(document).ready(function(){
loadstation();
});
function loadstation(){
$("#station_data").load("station.php");
setTimeout(loadstation, 2000);
}
station.php
<?php
include ("database.php");
$result = mysqli_query($con, "SELECT * FROM sql347511.1 ORDER BY ID DESC LIMIT 1;");
while ($row = mysqli_fetch_array($result))
{
echo "<div class='infobox_data' id='infobox_temp'>" . $row['TEMP'] . "°C</div>";
echo "<div class='infobox_data' id='infobox_humid'>" . $row['HUMID'] . "%</div>";
echo "<div class='infobox_time'>At " . date("g:i:s a F j, Y ", strtotime($row["TIME"])) . "</div>";
}
mysqli_close($con);
?>
Where to put the data
<div id="station_data"></div>
You can make inputs from div on double click and then get this inputs value through jquery:
$().val;
then using ajax send this value to php:
$.ajax({
url: 'url_to_php_which_update_mysql',
data: {'data': 'value_from_input'},
cache: false,
success: function(response){
$(input).val(response);
}
});
And in php file you need to upload $_GET['data'] in Database

php updates database data only sometimes

I have to following form
$connection = mysqli_connect(SQL_HOST, SQL_USERNAME, SQL_PASSWORD, SQL_DBNAME) ;
if (mysqli_connect_errno($connection))
{
echo "Nespojeno s MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM novinky";
$result = mysqli_query($connection, $sql);
echo "<div id='newsbox'>";
while($zaznam = mysqli_fetch_row($result)):
echo "<form class='newsholder'>";
echo "<input id='displaynadpis' value='$zaznam[1]'>";
echo "<input id='displaybold' value='$zaznam[2]'>";
echo "<textarea id='displaytext'>$zaznam[3]</textarea>";
echo "<div class='buttonsholder'>";
echo "<button class='deletebutton'>Smazat</button>";
echo "<button class='updatebutton'>Upravit</button>";
echo "<input id='prime' type='hidden' attr='id' value='$zaznam[0]'>";
echo "</div>";
echo "<div class='clearfix'></div>";
echo "</form>";
endwhile;
echo "</div>";
mysqli_close($connection);
that displays data from the database in order to update them upon the .updatebutton click.
The data is passed by jquery ajax
$('.updatebutton').on('click', function(){
var idVal = $(this).closest('.newsholder').find('#prime').val();
var displaynadpisVal = $(this).closest('.newsholder').find('#displaynadpis').val();
var displayboldVal = $(this).closest('.newsholder').find('#displaybold').val();
var displaytextVal = $(this).closest('.newsholder').find('#displaytext').val();
alert(displaynadpisVal);
$.ajax({url:"updaterecord.php",
type:"POST",
cache:false,
data:{id: idVal, displaynadpis: displaynadpisVal, displaybold: displayboldVal, displaytext: displaytextVal}
}); });
to the php script
$connection = mysqli_connect(SQL_HOST, SQL_USERNAME, SQL_PASSWORD, SQL_DBNAME) ;
if (mysqli_connect_errno($connection))
{
echo "Nespojeno s MySQL: " . mysqli_connect_error();
}
$id = $_POST['id'];
$updatenadpis = $_POST['displaynadpis'];
$updatetextbold = $_POST['displaybold'];
$updatetext = $_POST['displaytext'];
echo $updatetext;
$sql = "UPDATE novinky SET nadpis='$updatenadpis',
textbold='$updatetextbold',
text='$updatetext'
WHERE id = '$id'"
;
$retval = mysqli_query($connection, $sql);
if(! $retval )
{
die('Could not enter data: ' . mysqli_connect_error());
}
echo "Entered data successfully\n";
mysqli_close($connection);
to update the database. The problem is, that it only works sometimes, but in about 70% of cases it doesn't make any change. The data is stored in js variables just fine, when tested by alert(), they exist everytime. So the problem must be in the mysqli_query() possibly? Or the AJAX method? I have tried a lot of options and recommendations from other posts but no luck. Thanks for your help...
Biggest problem here is fact that you are passing raw user input to query. Assigning it to variable doesn't change anything!
You should filter everything received from user and use prepared statements to be sure that you are safe.
Also don't use mysqli_connect_error() to check query errors. Use mysqli_error().

Categories