PHP/jQuery AJAX algorithm only working every other time - php

I am trying to build a page that uses jQuery to call a database every second and return the highest numbered row.
The jQuery code is below (this is in $('document').ready)
var id = 0;
$.post('check.php', 'id=0', function(data){
id = parseInt(data);
$('h1').text(data);
});
var timer = setInterval(function() {
$.post('check.php', 'id=' + id, function(data){
if (data != '')
$('h1').text(data)
else
$('h1').text("NOTHING!");
id = parseInt(data);
});
}, 1000);
And the PHP file, check.php, has the following code (after connecting to the database):
$id = $_POST['id'] - 1;
$query = "SELECT * FROM testtable WHERE 'id' > $id ORDER BY id DESC";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
echo "$row[0]";
When 'id' is the first column.
The highest row number right now is 13. I would expect it to send 13 to the PHP file. $id would then be 12, so it would select all rows with id values higher than 12, returning the row with id value 13. Then it would echo "13", which is sent back to jQuery, which is parsed to an integer, making id equal to 13. Then 13 is sent to the PHP file again a minute later, and the process cycles.
What's actually happening is that it's alternating between displaying "13" and "NOTHING!", and I can't figure out why.

Because select * from tesstable where id > 13 will always be an empty result if 13 is the highest id. What you want is this:
select max(id) as id from testtable
You don't have to send back $id, and if it's got an index on it, this query will return very quickly.
Also, your original query has the column id in quotes, not backticks. You're comparing the string "id" with your variable $id. To top that off, you're susceptible to SQL injection here, so use mysql_escape_string, PDO, or remove the variable reference altogether using the max query provided.

I'll suggest you to do it like this.Try it.And tell if it's working.
var id = 0,count = 0;
$.post('check.php', {id:0}, function(data){
id = +data["rows"]; // Try parse or just a +
$('h1').text(data);
count++;
},"json");
var timer = setInterval(function() {
$.post('check.php', {id:id-count}, function(data){
if (data["rows"] != null || data["rows"] != "")
$('h1').text(data)
else
$('h1').text("NOTHING!");
id = +data["rows"];
count++;
},"json");
}, 1000);
$id = $_POST['id'];
$queryString = ($id == 0) ? "'id' > $id" : "'id' = $id";
$query = "SELECT * FROM testtable WHERE $queryString ORDER BY id DESC";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
echo json_encode(array("rows" => "$row[0]");

Related

Fetch hidden product_id from database to jquery autocomplete plugin list

I am using jquery autocomplete plugin for selecting data from database using PHP, MySql and Ajax.
The plugin operates good except fetching the product_id. When the plugin fetches the autocomplete list I want also to attach a hidden product_id to the products to differentiate the products for example in case of multiple products with the same product_name.
Below is the code that functions only with product_name.
function select_name(){
$("[id^='product_name']").focus(function() {
var id = $(this).attr('id');
id = id.replace("product_name",'');
$("[id^='product_name']").autocomplete({
source: 'store_supply/fetch_autocomplete_name.php',
select: function (event, ui) {
var pro_nm = ui.item.value;
$.ajax({
url:"store_supply_manage/fetch_product_code.php",
method:"POST",
data:{pro_nm:pro_nm},
//here I want to post a product_id when selecting the product_name
dataType:"json",
success:function(data){
$('#mu_emri_'+id).val(data.mu_name);
$('#product_code_'+id).val(data.barCode);
$('#vat_vlera_'+id).val(data.vat_value_4);
$('#product_id'+id).val(data.product_id);
calculateTotal();
}
});
}
});
});
}
//fetch_autocomplete.php
if (isset($_GET['term'])) {
$term = $_GET['term'];
$query = $db->prepare("SELECT product_name FROM products
WHERE product_name LIKE '%$term%' LIMIT 10");
$query->execute();
$nr = $query->rowCount();
if ($nr > 0) {
while ($row = $query->fetch()) {
$result[] = $row['product_name'];
}
}
else {
$result = array();
}
//return json result
echo json_encode($result);
}
In your code you are preparing your SQL statement but interpolating the $term variable instead of parameterizing your query. In the example below I have parameterized your query.
As shown in the documentation, the data can be either:
An array of strings: [ "Choice1", "Choice2" ]
An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]
So you can just change your fetch_autocomplete.php to something like:
if (isset($_GET['term'])) {
$term = '%' . $_GET['term'] . '%';
// parameterized query in nowdoc*
$sql = <<<'SQL'
SELECT id AS `value`, product_name AS `label`
FROM products
WHERE product_name LIKE :term
LIMIT 10
SQL;
// prepare the query
$query = $db->prepare($sql);
// bind variables and execute
$query->execute(['term'] => $term);
// As fetchAll() returns an empty array if there are no matching
// rows we do not need to check rows returned
$result = $query->fetchAll(PDO::FETCH_OBJ);
// return json result
echo json_encode($result);
}
* nowdoc
Change id to whatever the name of your product id column is. Now, inside your select handler, ui.item.value will be the product id instead of its name.

How to retrieve multiple data from ajax post function?

I have a select dropdown list and some input fields. My goal is when I select any option from the dropdown list it takes it's value and insert it into the input fields, and that is the ajax post function
<script>
$(document).ready(function(){
$('#productSelect').on('change',function(){
var selectedValue = $('#productSelect').val();
$.post('php/loadProducts.php', {
productId : selectedValue
}, function(data, status) {
$('#id').val(data);
$('#name').val(data);
$('#price').val(data);
});
});
});
</script>
and that is what happens in the "loadProdcut.php" file
<?php
if (isset($_POST['productId'])) {
$productId = $_POST['productId'];
$sql = "SELECT * FROM products WHERE product_id = '$productId';";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$Id = $row['product_id'];
echo $Id;
$Name = $row['product_name'];
echo $Name;
$Price = $row['product_price'];
echo $Price;
}
};
}
?>
Now when I select any option of the dropdown list it inserts all the values (id, name and price) in every single input field, so what I want to achieve is to place every single value into it's input feild.
It's simpler and more reliable to return JSON from an AJAX call to the server if for no other reason than you then return it all in one lump rather than in multiple echo's
Also a prepared statement protects you from bad actors attempting to mess up your database.
I am assuming as you are using a product_id to access a product table there will be only one row returned, so the loop is unnecessary
<?php
if (isset($_POST['productId'])) {
// query with prameter ?
$sql = "SELECT product_id, product_name, product_price
FROM products WHERE product_id = ?";
// prepare it
$stmt = $conn->prepare($sql):
// bind the parameter to its data
$stmt->bind_values('i', $_POST['productId']);
$stmt->execute();
// get resultset from the execution of the query
$result = $stmt->get_result();
$row = $result->fetch_assoc();
//return the row (an array) converted to a JSON String
echo json_encode($row);
}
Now you need to amend the javascript to process the nice object you have just returned.
<script>
$(document).ready(function(){
$('#productSelect').on('change',function(){
var selectedValue = $('#productSelect').val();
$.post('php/loadProducts.php', {productId : selectedValue}, function(data, status) {
$('#id').val(data.product_id);
$('#name').val(data.product_name);
$('#price').val(data.product_price);
});
});
});
</script>

PHP Use an API to select a specific value from a table by its ID

So this is the code I have so far, I'm leaving out the code I used to connect to the database since that's not important and isn't the problem.
$id = strip_tags(mysql_real_escape_string($_GET['id']));
$sql_value = "SELECT value FROM table";
$sql = mysql_query("UPDATE table SET value='[idk what to do here]' WHERE id='$id'");
so the $id selects the id from the url or API and the $sql_value selects the values from the table.
I want the value in the same row as the id specified to increment by 1
E.G.
id = 0, value = 0;
id = 1, value = 0;
id = 2, value = 0;
id = 3, value - 0;
If in the API I type: "id=2"
I want the PHP script to increment the corresponding "value" by 1
E.G.
id = 0, value = 0;
id = 1, value = 0;
id = 2, value = 1;
id = 3, value - 0;
Assuming that your value field is an INT. You can do that by:
"UPDATE table SET value=value+1 WHERE id='$id'"
But i strongly recommend you to take a look at mysqli or PDO and start to make prepared statements to handle the data. See more here:
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/manual/en/pdo.prepare.php
Use:
$sql = mysql_query("UPDATE table SET value=value+1 WHERE id='$id'");
As long as the value is an int this will work:
UPDATE table SET value=value + 1 WHERE id='$id'
UPDATE tablename t SET value = ( t.value+1 ) WHERE t.id = '$id'
Do you want?
"UPDATE table SET value=value+1 WHERE id='$id'"???

How to add item/post to favourites

I'm trying to create a button which will allow users to favourite certain posts using php and jquery (ajax). I've been trying to use This answer on here to get it all working, but I'm having trouble with getting the post id specific to the post that is meant to be favourited and instead it always gives the post id of the last post to be loaded on the page. Here's my code as it is, but I suspect I've probably just made a mistake in adapting it.
I have 3 tables; Users, Posts and Favourites. In Users I have username password and id, Posts I have id (and content) and in Favourites I have id, userid and postid.
Jquery:
<script>
$(document).ready(function() {
$('.favourite').on('click', null, function() {
var _this = $(this);
var postid = _this.data('$postid');
$.ajax({
type : 'POST',
url : '/add.php',
dataType : 'json',
data : '$postid='+ postid,
complete : function(data) {
if(_this.siblings('.favourite'))
{
_this.html('<img src="add2.png" />');
}
else
{
_this.html('<img src="add1.png />');
}
}
});
});
});
</script>
Main PHP (index.php):
<?php
$getposts = mysql_query("SELECT * FROM Posts ORDER BY id DESC") or die(mysql_query());
while ($row = mysql_fetch_assoc($getposts))
{
$id = $row['id'];
$user = $_SESSION['user'];
$findid = mysql_query("select * from Users where username='$user'");
if ($rows = mysql_fetch_assoc($findid));
{
$userid= $rows['id'];
$postid= $id;
}
echo '<img src="add1.png" />';
}
?>
(There is other code, but it's not related to this section.)
add.php:
<?php
session_start();
require_once('connect.php');
$userid = $_SESSION['$id'];
$postid = $_SESSION['$postid'];
$query_favorite = "SELECT userid, postid FROM Favourites";
$favorite = mysql_query($query_favorite) or die(mysql_error());
$row_favorite = mysql_fetch_assoc($favorite);
$totalRows_favorite = mysql_num_rows($favorite);
if(in_array($_POST['id'], $row_favorite))
{
$Del="DELETE FROM Favourites WHERE userid='$userid' AND postid='$postid'";
$result = mysql_query($Del);
}
else
{
$Add = "INSERT INTO Favourites (userid, postid) VALUES ('$userid', '$postid')";
$result = mysql_query($Add);
}
?>
Thanks in advance for any assistance!
In main.php you are using data-id="' . $postid . '".
Which inserts the postId into the HTML, right?
But in your Javascript you are trying to fetch this data element with
var postid = _this.data('$postid');
data : '$postid='+ postid,
instead of
var post_id = _this.data('id');
data : 'id='+ post_id,
Because your data attribute isn't data-$postid, but data-id.
Same error in add.php:
$userid = $_SESSION['$id'];
$postid = $_SESSION['$postid'];
without single-qoutes:
$userid = $_SESSION[$id];
$postid = $_SESSION[$postid];
Because, when you single-quote the variable, then its the string "$id",
which isn't in $_SESSION.
and you have to fetch $id(postid) from the $_POST data send with your AJAX request. The code missing is: json_decode incoming POST and grab the id, then use it...
Debugging hints:
test that the data is inserted into HTML
add var_dump($_POST); to add.php in order to see the data the AJAX requests posts. The "id" should be part of it.
json_decode() the incoming $_POST to get the ID
and then use it on other variables

Checking to see if a MySQL row is populated

I have a page that writes to a MySQL table. The table has a set amount of rows (24).
I have an $id variable that's set by a rand() function. I basically want to pull the row at that $id, so if $id was 3, I want to pull the third row. Then, I want to check if there is a price set at that row (indicating that the row is being used). If there is no price, I want to keep $id at the value it has been set at and proceed with the query. If there is a price, I want to re-randomize the $id variable, and check again if that row is used up. When it finds an empty row, proceed with the query.
My solution semi-works, but it seems to have a <10% chance of overwriting a used row, for some reason. I want it to never overwrite a used row.
Here's my code:
mysql_select_db("delives0_booklet", $con);
$query = "SELECT * FROM booklet WHERE id = '$id'";
$res = mysql_query($query,$con);
$newId = $id;
while($row = mysql_fetch_array($res))
{
if($row['price'] != 0)
{
do{
$newId = rand(1, 24);
}while($newId == $id);
}
}
$id = $newId;
mysql_query("UPDATE booklet SET price = '$price', advertiser = '$advertiser', image = '$image', monthsRemaining = '$monthsRemaining', availability = 1 WHERE id = '$id'");
Edit
I had the idea to do this. I loop through the table and I put the 'id' of each unfilled spot into an array. Then I pick randomly from that array. However, there seems to be a bug that I can't find, since the array keeps showing as having nothing in it, even after the loop is run, and $i is the correct figure.
mysql_select_db("delives0_booklet", $con);
$query = "SELECT * FROM booklet";
$res = mysql_query($query,$con);
$i = 0;
$isEmpty = array();
while($row = mysql_fetch_array($res))
{
if($row['price'] == 0)
{
$isEmpty[i] = $row['id'];
$i = $i + 1;
}
}
echo $i . " unfilled spots.";
$n = 0;
while($n<$i)
{
echo $isEmpty[$n];
$n = $n + 1;
}
if($i > 0)
{
$id = $isEmpty[rand(0, $i)];
}
if($i == 0)
{
echo 'All spots have been filled.';
}
I think it is a top level logic problem. Because you populate with random ids, you can get duplicate ids, and so when you update "WHERE id = '$id'" you may be picking up rows already populated.
I don't know your goal, but perhaps using an auto-increment id, and dropping rows that you want to get rid of, is the way to go. A rolling set of rows (24 at a time) but with ever increasing ids, would prevent mistaking one for the other.
If I understand the problem correct, this should work:
SELECT *
FROM booklet
WHERE price = 0 OR price IS NULL
ORDER BY RAND()

Categories