MYSQL DELETE INNER JOIN only shows deletes after page reload - html

I have managed to get working a Duplicate field Check using INNER JOIN with PHP MYSQL , however the delete only shows after a page reload , the 1st time i load the page the duplicate entry's are shown then i reload the page and the DELETES are no longer showing. i dont understand why, does this code show any reason for this to happen? a page refresh does not happen no matter what code i use, nothing is run during the IF ($RowsDC >1) check other than the DELETE statement
here is the code:
while($row = $stat->fetch()){
//checking for duplicates
try {
$db2 = new PDO("mysql:host=localhost;dbname=classifieds2", 'root', ''); // 1. set database with this instead of conect - or change conect to this
$db2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$queryDC="SELECT * FROM listings WHERE listID = ? AND UID = ? ";
$statDC=$db2->prepare($queryDC);
$statDC->execute(array("$listID","$UID"));
$ResultDC = $statDC->fetchAll();
$RowsDC = count($ResultDC);
if ($RowsDC >1){ $db2A = new PDO("mysql:host=localhost;dbname=classifieds2", 'root', ''); // 1. set database with this instead of conect - or change conect to this
$db2A->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query01DC="DELETE a FROM listings a INNER JOIN listings a2 WHERE a.id < a2.id AND a.listID = a2.listID ";
$stat01DC=$db2A->prepare($query01DC);
$stat01DC->execute();
??? here i have tried to refresh the page but it does not no matter how i try nothing is run ???
}
}
catch (PDOException $e){
$_SESSION['message']="Database Error #vbmDUPCHECK2 <br> <h6><h6>Signed Out For Security Reasons</h6></h6>";
$_SESSION['loggedin']='000';
echo $errorcall;
die();
exit();
}
}//WHILE END

Related

SQL SELECT query excluding an array of id's for infinite scroll [duplicate]

I have followed help located in this topic: Using infinite scroll w/ a MySQL Database
And have gotten close to getting this working properly. I have a page that is displayed in blocks using jquery masonry, in which the blocks are populated by data from a mysql database. When I scroll to the end of the page I successfully get the loading.gif image but immediately after the image it says "No more posts to show." which is what it should say if that were true. I am only calling in 5 posts initially out of about 10-15, so the rest of the posts should load when I reach the bottom of the page but I get the message that is supposed to come up when there really aren't any more posts.
Here is my javascript:
var loading = false;
$(window).scroll(function(){
if($(window).scrollTop() == $(document).height() - $(window).height()) {
var h = $('.blockContainer').height();
var st = $(window).scrollTop();
var trigger = h - 250;
if((st >= 0.2*h) && (!loading) && (h > 500)){
loading = true;
$('div#ajaxLoader').html('<img src="images/loading.gif" name="HireStarts Loading" title="HireStarts Loading" />');
$('div#ajaxLoader').show();
$.ajax({
url: "blocks.php?lastid=" + $(".masonryBlock:last").attr("id"),
success: function(html){
if(html){
$(".blockContainer").append(html);
$('div#ajaxLoader').hide();
}else{
$('div#ajaxLoader').html('<center><b>No more posts to show.</b></center>');
}
}
});
}
}
});
Here is the php on the page the blocks are actually on. This page initially posts 5 items from the database. The javascript grabs the last posted id and sends that via ajax to the blocks.php script, which then uses the last posted id to grab the rest of the items from the database.
$allPosts = $link->query("/*qc=on*/SELECT * FROM all_posts ORDER BY post_id DESC LIMIT 5");
while($allRows = mysqli_fetch_assoc($allPosts)) {
$postID = $link->real_escape_string(intval($allRows['post_id']));
$isBlog = $link->real_escape_string(intval($allRows['blog']));
$isJob = $link->real_escape_string(intval($allRows['job']));
$isVid = $link->real_escape_string(intval($allRows['video']));
$itemID = $link->real_escape_string(intval($allRows['item_id']));
if($isBlog === '1') {
$query = "SELECT * FROM blogs WHERE blog_id = '".$itemID."' ORDER BY blog_id DESC";
$result = $link->query($query);
while($blogRow = mysqli_fetch_assoc($result)) {
$blogID = $link->real_escape_string($blogRow['blog_id']);
$blogTitle = $link->real_escape_string(html_entity_decode($blogRow['blog_title']));
$blogDate = $blogRow['pub_date'];
$blogPhoto = $link->real_escape_string($blogRow['image']);
$blogAuthor = $link->real_escape_string($blowRow['author']);
$blogContent = $link->real_escape_string($blogRow['content']);
//clean up the text
$blogTitle = stripslashes($blogTitle);
$blogContent = html_entity_decode(stripslashes(truncate($blogContent, 150)));
echo "<div class='masonryBlock' id='".$postID."'>";
echo "<a href='post.php?id=".$blogID."'>";
echo "<div class='imgholder'><img src='uploads/blogs/photos/".$blogPhoto."'></div>";
echo "<strong>".$blogTitle."</strong>";
echo "<p>".$blogContent."</p>";
echo "</a>";
echo "</div>";
}
}
Here is the php from the blocks.php script that the AJAX calls:
//if there is a query in the URL
if(isset($_GET['lastid'])) {
//get the starting ID from the URL
$startID = $link->real_escape_string(intval($_GET['lastid']));
//make the query, querying 25 fields per run
$result = $link->query("SELECT * FROM all_posts ORDER BY post_id DESC LIMIT '".$startID."', 25");
$html = '';
//put the table rows into variables
while($allRows = mysqli_fetch_assoc($result)) {
$postID = $link->real_escape_string(intval($allRows['post_id']));
$isBlog = $link->real_escape_string(intval($allRows['blog']));
$isJob = $link->real_escape_string(intval($allRows['job']));
$isVid = $link->real_escape_string(intval($allRows['video']));
$itemID = $link->real_escape_string(intval($allRows['item_id']));
//if the entry is a blog
if($isBlog === '1') {
$query = "SELECT * FROM blogs WHERE blog_id = '".$itemID."' ORDER BY blog_id DESC";
$result = $link->query($query);
while($blogRow = mysqli_fetch_assoc($result)) {
$blogID = $link->real_escape_string($blogRow['blog_id']);
$blogTitle = $link->real_escape_string(html_entity_decode($blogRow['blog_title']));
$blogDate = $blogRow['pub_date'];
$blogPhoto = $link->real_escape_string($blogRow['image']);
$blogAuthor = $link->real_escape_string($blowRow['author']);
$blogContent = $link->real_escape_string($blogRow['content']);
$blogTitle = stripslashes($blogTitle);
$blogContent = html_entity_decode(stripslashes(truncate($blogContent, 150)));
$html .="<div class='masonryBlock' id='".$postID."'>
<a href='post.php?id=".$blogID."'>
<div class='imgholder'><img src='uploads/blogs/photos/".$blogPhoto."'></div>
<strong>".$blogTitle."</strong>
<p>".$blogContent."</p>
</a></div>";
}
}
echo $html;
}
I have tried using the jquery infinite-scroll plugin, but it seemed much more difficult to do it that way. I don't know what the issue is here. I have added alerts and did testing and the javascript script is fully processing, so it must be with blocks.php right?
EDIT: I have made a temporary fix to this issue by changing the sql query to SELECT * FROM all_posts WHERE post_id < '".$startID."' ORDER BY post_id DESC LIMIT 15
The blocks are now loading via ajax, however they are only loading one block at a time. The ajax is sending a request for every single block and they are fading in one after another, is it possible to make them all fade in at once with jquery masonry?
I seen your code in another answer, and I would recommend using the LIMIT functionality in MySql instead of offsetting the values. Example:
SELECT * FROM all_posts ORDER BY post_id DESC LIMIT '".(((int)$page)*5)."',5
This will just take a page number in the AJAX request and get the offset automatically. It's one consistent query, and works independent of the last results on the page. Send something like page=1 or page=2 in your jQuery code. This can be done a couple different ways.
First, count the number of elements constructed on the page and divide by the number on the page. This will yield a page number.
Second, you can use jQuery and bind the current page number to the body:
$(body).data('page', 1)
Increment it by one each page load.
Doing this is really the better way to go, because it uses one query for all of the operations, and doesn't require a whole lot of information about the data already on the page.
Only thing to note is that this logic requires the first page request to be 0, not 1. This is because 1*5 will evaluate to 5, skipping the first 5 rows. If its 0, it will evaluate to 0*5 and skip the first 0 rows (since 0*5 is 0).
Let me know any questions you have!
Have you tried doing any debugging?
If you are not already using, I would recommend getting the firebug plugin.
Does the ajax call return empty? If it does, try echoing the sql and verify that is the correct statement and that all the variables contain the expected information. A lot of things could fail considering there's a lot of communication happening between client, server and db.
In response to your comment, you are adding the html in this piece of code:
if(html){
$(".blockContainer").append(html);
$('div#ajaxLoader').hide();
}
I would do a console.log(html) and console.log($(".blockContainer").length) before the if statement.

PHP prevent MySQL race condition

I am trying to prevent users joining at the "same time" from selecting the same available admin.
What i'm doing is:
$conn->beginTransaction();
$sth = $conn->query("SELECT admin,room FROM admins WHERE live = 1 AND available = 1 ORDER BY RAND() LIMIT 1 FOR UPDATE");
$free_admin = $sth->fetch();
if (!empty($free_admin)) {
$conn->query("UPDATE admins SET available = 0 WHERE room = " . $free_admin['room']);
.
.
$conn->commit();
} else {
$conn->rollBack();
}
Unfortunately it's not really working. When there is a high traffic, many users end up selecting the same free admin which causes an issue.
How can i lock a SELECTED row so i can read it and update it by only one user before any other user can read it?
In the updatestatement, use
WHERE room = ... AND availabe = 1
After the query, check mysql affected_rows to verify you did change the availability succesfully, and if not, restart.

Using MD5 and CONCAT in MuSQL WHERE clause

I am creating a reset password procedure. this way:
1- Send reset email to the user (whom forgot his/her password), and this email contain a link to this address:
http://www.example.com/resetpassword.php?userid=1b2798bad6ee465d967cdb71ced504f7
The value of the parameter [userid] is generated by this PHP code:
<?php
md5($row_Recordset2['userID'].date('d-m-Y'));
?>
Note: I did this so that I can get a unique parameter value containing: The MD5 hash of the real user id + the current date (concatenation) , Why? so the link in the email will be available for the current date only. I do not want that link to work in the next day.
2- When the person click on the above link, he/she will be taken to the page [resetpassword.php]
3- In the page [resetpassword.php] page I have this piece of code:
$colname_Recordset1 = "-1";
if (isset($_GET['userid'])) {
$colname_Recordset1 = $_GET['userid'];
}
mysql_select_db($database_aaa_database, $aaa_database);
$query_Recordset1 = sprintf("SELECT * FROM users WHERE md5(CONCAT(userID,
DATE_FORMAT(NOW(),'%d-%m-%Y'))) = %s ", GetSQLValueString($colname_Recordset1,
"text"));
$Recordset1 = mysql_query($query_Recordset1, $aaa_database) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
The SELECT statement return [Query was empty] ... What is the problem and how to solve it?
I have tested this MySQL statement manually:
SELECT userFirstName, md5(CONCAT(userID, DATE_FORMAT(NOW(),'%d-%m-%Y'))) from users
And it return many rows, one of the rows is like this:
Sam 1b2798bad6ee465d967cdb71ced504f7
So, the:
md5(CONCAT(userID, DATE_FORMAT(NOW(),'%d-%m-%Y')))
works fine and it return the same exact value generated by the PHP code :
<?php
md5($row_Recordset2['userID'].date('d-m-Y'));
?>
PHP give: 1b2798bad6ee465d967cdb71ced504f7
MySQL give: 1b2798bad6ee465d967cdb71ced504f7
But this:
md5(CONCAT(userID, DATE_FORMAT(NOW(),'%d-%m-%Y')))
seems to be NOT WORKING in the WHERE clause:
sprintf("SELECT * FROM users WHERE md5(CONCAT(userID,
DATE_FORMAT(NOW(),'%d-%m-%Y'))) = %s ", GetSQLValueString($colname_Recordset1,
"text"));
By the way, I am using Dreamweaver.
I don't know how to solve this problem. Any help will be highly appreciated.

mysql update 2 blobs at once not working

i'm having an issue when trying to update two BLOB fields in a row using mysql and php commands.
Inserting the BLOBs into the row seems to work no problem, here is what I do.
$logotemp = $_FILES['eventlogo']['tmp_name'];
$thumbnailtemp = $_FILES['eventthumbnail']['tmp_name'];
$openlogo = fopen($logotemp, 'r');
$openthumbnail = fopen($thumbnailtemp, 'r');
$logo = fread($openlogo, filesize($logotemp));
$logo = addslashes($logo);
$thumbnail = fread($openthumbnail, filesize($thumbnailtemp));
$thumbnail = addslashes($thumbnail);
fclose($openlogo);
fclose($openthumbnail);
So I have two form file inputs, and those files are read, and then set as the variables $log and $thumbnail. I then use the following command to enter this into the DB:
$qry = "INSERT INTO $table (`Event Logo`, `Venue Logo`) VALUES ('$logo', '$thumbnail')";
$result = mysql_query($qry);
if(!$result) {
die(mysql_error());
}
The above works fine, although I have trimmed out the rest of the fields that also get filled. The query works, and I can return the images to a page, and then display them along with all of the other information from that row.
I then want to edit the row, so created a new php file called edit.php, which is a copy of the php file used above, called new.php.
This means that the form is identical, and when the page is displayed, the value for each input is prefilled with the info from the database, the logo and thumbnail are shown next to the upload fields.
If I then run a query to update the row, using almost the same code as above, it always enteres an empty value into both blobs, essentially deleting the uploaded images. Here is what happens:
$id = $_POST['eventid'];
$logotemp = $_FILES['eventlogo']['tmp_name'];
$openlogo = fopen($logotemp, 'r');
$logo = fread($openlogo, filesize($logotemp));
$thumbnailtemp = $_FILES['eventthumbnail']['tmp_name'];
$openthumbnail = fopen($thumbnailtemp, 'r');
$thumbnail = fread($openthumbnail, filesize($thumbnailtemp));
fclose($openlogo);
fclose($openthumbnail);
So once again, the form fields are still called eventlogo and eventthumbnail, and the variables are still $logo and $thumbnail. I then use the following query to update the row:
$qry = "UPDATE $table SET `Event Name` = '$name', `Date` = '$date', `Time` = '$time', `Venue` = '$venue', `Price` = '$price', `Open To` = '$opento', `Rep Name` = '$repname', `Rep Email` = '$repemail', `Address` = '$address', `Website` = '$website', `Phone` = '$phone', `Description` = '$description', `Event Logo` = '$logo', `Venue Logo` = '$thumbnail' WHERE `Event ID` = '$id'";
I have left in the other variables that are updated this time.
$result = mysql_query($qry);
if(!$result) {
die(mysql_error());
}
When the query runs, it will update any other fields I want, except for the two image BLOB fields at the end. Considering I copied and pasted the code for the upload fields, the code to read the contents of that field, and then manually typed out a query to update those fields, I can't see what's going wrong.
Am I missing something obvious? Any help is greatly appreciated.
Thanks, Eds
Cant find the code I sorted this with, but I think I ended up just updating one at a time.

mySQL insert HTML form posting problem on results... Need help

I am stumped!! I can't figure this out.
I created an HTML form that inserts a record into mySQL. It works and I can see the new records I add/insert. BUT, I get the wrong confirmation page: I get a the FAIL PAGE instead of the SUCCESS page. I see the new record but I always get taken to the fail page. Why?
Is there something wrong with the script or a setting inside mySQL?
Here is my form post script:
<?
$host="XXXXXXXXXXXX";
$username="XXXXXXXX";
$password="XXXXXXXX";
$db_name="XXXXXXXXX";
$tbl_name="cartons_current";
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$order = "INSERT INTO cartons_current (type, part_no, description, count,
size, min, max, qty)
VALUES
('$_POST[type]', '$_POST[part_no]', '$_POST[description]', '$_POST[count]',
'$_POST[size]', '$_POST[min]', '$_POST[max]', '$_POST[qty]')";
$result = mysql_query($order);
$result = mysql_query($order); //order executes
if ($result) {
$part_no = $_REQUEST['part_no'] ;
header("location: inv_fc_result_new_success.php?part_no=" . urlencode($part_no));
}
else {
header("location: inv_fc_result_new_fail.php");
}
?>
Your code looks OK, except for the possibility that mysql_query() gets called twice. If that is actual code, then I suspect the first call loads the record you are seeing, and the subsequent call returns the error message.
$result = mysql_query($order);
$result = mysql_query($order); //order executes
You appear to be calling mysql_query twice. If it's not a typo in copying the code onto stackoverflow then this could be the issue.
The first call is returning true but second call is returning 'false' hence the fail page is displayed