limit entry to db while added new records - php

ok i have this recent visits table and the following code i use to enter records into the table user wise
if($user->is_logged_in() ){
$postid = $row['postid'];
$uid = $_SESSION['memberid'];
$stmt = "SELECT * FROM recent WHERE postid = :postid AND memberid = :memberid";
$stmt = $db->prepare($stmt);
$stmt->bindParam(':postid', $postid, PDO::PARAM_STR);
$stmt->bindParam(':memberid', $uid, PDO::PARAM_STR);
$stmt->execute();
$recentCount = $stmt->rowCount();
if(!$recentCount)){
$stmt = $db->prepare('INSERT INTO recent (postid,memberid) VALUES ( :postid,:memberid)');
$stmt->execute(array(
':postid' => $postid,
':memberid' => $uid
));
}
}
but the thing is i wish to limit records, as in per user only 50 records should be in db. supposing user visits a new topic then if there already 50 records in recent table for the user then the number 50 gets deleted and 49 record becomes 50. i hope you get my point?
its just that records per user should not exceed above 50 is what i mean.

Based on the question and comments, I think you can do it like this (you didn't mention the name of your date field but for this example I'll assume it's called createddate):
if($user->is_logged_in() ){
$postid = $row['postid'];
$uid = $_SESSION['memberid'];
$stmt = "SELECT COUNT(*) FROM recent WHERE postid = :postid AND memberid = :memberid"; //let mysql count the rows
$stmt = $db->prepare($stmt);
$stmt->bindParam(':postid', $postid, PDO::PARAM_STR);
$stmt->bindParam(':memberid', $uid, PDO::PARAM_STR);
$stmt->execute();
$recentCount = $stmt->fetchColumn(); //fetch first column in first row, this will be the count result
if($recentCount >= 50)
{
$stmt2 = $db->prepare('DELETE FROM recent WHERE createddate = (select min(createddate) where memberid = :memberid)');
$stmt2->bindParam(':memberid', $uid, PDO::PARAM_STR);
$stmt2->execute();
}
$stmt = $db->prepare('INSERT INTO recent (postid,memberid) VALUES ( :postid,:memberid)');
$stmt->execute(array(
':postid' => $postid,
':memberid' => $uid
));
Apologies if the PDO syntax is wrong, I haven't used it in a while. I'm sure you can make that right yourself. But the important thing is the structure of the PHP "if" statement and the "delete" SQL.

Related

SQL insert into select issue

So i think i'm close to figuring this out but my query won't add the item from the "pending" table to the "items" table. can you guys help me out with this please. Also if i want it to delete after it gets added should i add the code below the INSERT INTO SELECT query? thanks
action.php:
$sql = "INSERT INTO items (photo,title,description, name) SELECT (photo,title,description, name) FROM pending";
$stmt = $conn->prepare($sql);
$stmt->execute();
Example for delete query after it takes the item from the "pending" into items:
$idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT);
//try deleting record using the record ID we received from POST
$sql = "DELETE FROM pending WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $idToDelete, PDO::PARAM_INT);
$stmt->execute();
I think you are leaving yourself open to mistakes doing it this way.
Consider what would happen if a new row is added to the pending queue after you have issued the INSERT SELECT but before you have started your delete.
I think you need to do this in a more controlled way inside a single loop to make sure you are only deleting what you have copied from pending into items.
$sql = "SELECT photo,title,description, name FROM pending";
$select_pending = $conn->prepare($sql);
$select_pending->execute();
$sql = "INSERT INTO items (photo,title,description, name)
VALUES (:photo,:title,:description, :name)";
$insert_items = $conn->prepare($sql);
$sql = "DELETE FROM pending WHERE id = :id";
$delete_pending = $conn->prepare($sql);
// only if you are using INNODB databases.
//$conn->beginTransaction();
while( $row = $select_pending->fetch_object() ) {
$insert_items->bindParam(':photo', $row->photo, PDO::PARAM_STR);
$insert_items->bindParam(':title', $row->title, PDO::PARAM_STR);
$insert_items->bindParam(':description', $row->description, PDO::PARAM_STR);
$insert_items->bindParam(':name', $row->name, PDO::PARAM_STR);
$insert_items->execute();
$delete_pending->bind_param(':id', $row->id, PDO::PARAM_INT);
$delete_pending->execute();
}
// only if you are using INNODB databases.
//$conn->commit();
$sql = "INSERT INTO items (photo,title,description, name)
SELECT photo,title,description, name FROM pending";
remove the () in the SELECT statement.

Code inserted triplicate records a few times and now works periodically

I have code that inserts a row in the points table when a user1 approves a post. I wrote code so that it only approves the post if the user is not the author of the post. There can be a maximum of 10 posts at any time to choose from for approve.
However, while this will only approve a post (and insert a record in points) if the current user is not the author of the post, it will not just insert the record for the post that is approved. Rather it will insert as many rows into points table as there are posts for user.
What I want to do is insert into points for a post that is approved by the current user where the post author is not the current user.
I am very close. This code works, except that it will insert all records if there are multiple posts by other users instead of just the one post that the current user chooses to approve.
$results2 = $dbh->prepare("select
wp_users.ID,
wp_users.display_name,
stories.ID AS ID1,
stories.SID,
writing.ID AS ID2,
writing.WID,
writing.text
FROM writing
LEFT JOIN stories on writing.SID = stories.SID
LEFT JOIN wp_users ON writing.ID = wp_users.ID
WHERE (stories.SID = $the_SID)
order by writing.WID asc limit 10
");
$results2->bindParam(':wp_users.ID', $user_ID, PDO::PARAM_INT);
$results2->bindParam(':display_name', $display_name, PDO::PARAM_STR);
$results2->bindParam(':stories.ID', $ID1, PDO::PARAM_INT);
$results2->bindParam(':stories.SID', $the_SID, PDO::PARAM_STR);
$results2->bindParam(':writing.WID', $WID, PDO::PARAM_STR);
$results2->bindParam(':writing.ID', $ID2, PDO::PARAM_INT);
$results2->bindParam(':text', $text, PDO::PARAM_STR);
$results2->execute();
$row2 = $results2->fetchAll(PDO::FETCH_ASSOC);
foreach ($row2 as $result5) {
$blurb = $result5['ID2'];
settype($blurb, "integer");
}
//PA APPROVE INSERT CONTROL
if(isset($_POST ['yes'])){
// Get values from form
$yes_WID = $_POST['yes'];
$yesupdate = "UPDATE writing SET approved = :approved, position = :position
WHERE WID = :WID";
$stmt2 = $dbh->prepare($yesupdate);
$stmt2->bindParam(':WID', $yes_WID, PDO::PARAM_INT);
$stmt2->bindParam(':approved', $e = Y, PDO::PARAM_STR);
$stmt2->bindParam(':position', $row2[0]['position'], PDO::PARAM_INT);
$stmt2->execute();
$yes_WID = $_POST['yes'];
//trying to give points as long as user is not the author
$contpoint = 3;
foreach($row2 as $result5){
if($blurb !== $user_ID){
$yesupdate2 = "INSERT INTO points(ID,
SID,
WID,
PID) VALUES(
:ID,
:SID,
:WID,
:PID)";
$stmt9 = $dbh->prepare($yesupdate2);
$stmt9->bindParam(':ID', $blurb, PDO::PARAM_INT);
$stmt9->bindParam(':SID', $the_SID, PDO::PARAM_INT);
$stmt9->bindParam(':WID', $yes_WID, PDO::PARAM_INT);
$stmt9->bindParam(':PID', $contpoint, PDO::PARAM_INT);
$stmt9->execute();
}
}
It would appear that your if condition is not being evaluated properly. Are $blurb and $user_ID the same type?
From http://php.net/manual/en/language.operators.comparison.php
$a != $b Not equal TRUE if $a is not equal to $b after type juggling.
$a !==$b Not identical TRUE if $a is not equal to $b, or they are not of
the same type.
What is the purpose of this code? It just sets $blurb to each of the values and then does nothing with the result unless the brace in between the code listings is not correctly shown. So is it a foreach inside of a foreach?
In any case, it does not appear that you set $user_ID as an integer in the same manner as you do for $blurb.
foreach ($row2 as $result5) {
$blurb = $result5['ID2'];
settype($blurb, "integer");
}
Do away with the first foreach loop and combine it with the second as such:
foreach($row2 as $result5){
$blurb = $result5['ID2'];
$userID = $result5['user_ID'];
settype($blurb, "integer");
settype($userID, "integer");
if($blurb !== $userID){
...etc

PHP PDO search for a value in two or more columns using one string

When I want to find a value from a row using PDO I use the following method:
//Search whether user exists
$sqlQueryEmailLogin = $dbh->prepare("SELECT vendor_id, first_name, last_name, email_login, user_password, passport_id, login_attempts, login_last_attempt FROM $tableVendorDetails WHERE email_login = ?");
$sqlQueryEmailLogin->bindValue(1, $emailLogin);
$sqlQueryEmailLogin->execute();
and the following PHP code for the search field
$emailLogin = 'xyz#abc.com'
Now I'd like to search two columns or more and use the following code
$sql = "SELECT * FROM articles WHERE id = ? AND status = ?";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, $id);
$stmt->bindValue(2, $status);
$stmt->execute();
I'd like to search the two columns from a string. How should I go about it, please?
The string value i go is from a html form with one input box
I'd like a string that is capable of searching two values from a MySQL table e.g.
$search = $id; and
$seach = $status;
in this case both cancel each other
You could simplify it by using the method described by #gbestard. But you should also do this:
$search = 'asdf'; // fill this with your form input
$sql = "SELECT * FROM articles WHERE id = :id OR status = :status";
$stmt = $conn->prepare($sql);
$stmt->execute(array(
':id' => $search,
':status' => $search,
));
Notice the change to OR in the query, and supplying the $search multiple times...
That's what I'm using
$sql = "SELECT * FROM articles WHERE id = :id AND status = :status";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':id' => $id , ':status' => $status));
Try the following
$sql = "SELECT * FROM articles WHERE id = :id AND status = :status";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':id', $id);
$stmt->bindValue(':status', $status);
$stmt->execute();
See docs http://php.net/manual/en/pdostatement.bindvalue.php
You should use OR instead of AND. That way, you will get all rows that match either by id or by status.
SELECT * FROM articles WHERE id = ? OR status = ?

Not getting a result from DB

So I'm checking to see if a user already liked a post. Here's what I'm doing
$id = 65;
//Get likes count
$stmt = $con->prepare("SELECT * FROM likes WHERE liked_post_id = :liked_post_id");
$stmt->bindValue(':liked_post_id', $id, PDO::PARAM_STR);
$stmt->execute();
$return = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<pre>
<?php
print_r($return);
?>
</pre>
<?php
//Get user IP
$ip = $_SERVER['SERVER_ADDR'];
//Check if user liked post
$result = $con->prepare("SELECT * FROM likes WHERE liked_post_user = :username");
$result->bindParam(':username', $_SESSION['user']);
$result->execute();
$reprint = $result->fetch(PDO::FETCH_ASSOC);
echo $reprint['liked_post_user'];
$return_cnt = count($reprint);
if($return_cnt < 1){
//Insert like
$query = $con->prepare("INSERT INTO likes (liked_post_id, liked_post_user, liked_post_ip) VALUES (:usr_id, :user, :ip)");
$query->bindValue(':usr_id', $id, PDO::PARAM_STR);
$query->bindValue(':user', $_SESSION['user']);
$query->bindValue(':ip', $ip, PDO::PARAM_STR);
$query->execute();
}
The problem is $query never gets ran. Even though I have no record of the username in the DB. So I'd expect it to run once, and insert $query into the DB, once. But it isn't. I'm not getting any errors either. Any ideas?
First of all you can simply count $reprint. To answer your second issue, you need to select the post, or else it'll simply check all the posts. So do
$result = $con->prepare("SELECT * FROM likes WHERE liked_post_user = :username AND liked_post_id = :post_id");
$result->bindParam(':username', $_SESSION['user']);
$result->bindParam(':post_id', $_GET['id']);
$result->execute();
$reprint = $result->fetch(PDO::FETCH_ASSOC);
Note that if no user is logged in it'll still input an empty value. So make sure to figure a way around that.
The second query should look for a specific liked_post_id. It's currently looking for any posts that the user liked, not just this one.
//Check if user liked post
$result = $con->prepare("SELECT * FROM likes WHERE liked_post_user = :username AND liked_post_id = :id");
$result->bindParam(':username', $_SESSION['user']);
$result->bindParam(':id', $id);
$result->execute();
$reprint = $result->fetch(PDO::FETCH_ASSOC);
And then you should test whether the query found anything by testing whether $reprint is an array or false:
if ($reprint) {
echo $reprint['liked_post_user'];
} else {
//Insert like
$query = $con->prepare("INSERT INTO likes (liked_post_id, liked_post_user, liked_post_ip) VALUES (:usr_id, :user, :ip)");
$query->bindValue(':usr_id', $id, PDO::PARAM_STR);
$query->bindValue(':user', $_SESSION['user']);
$query->bindValue(':ip', $ip, PDO::PARAM_STR);
$query->execute();
}

The script will not save the data to mysql

I am pulling my hair out about this script below. No mater what I do it will not save the data sent to it. I have set the script of many different ways and also tested it like I show below.
I have set the part that sends it to the script like this $pid = 6 $emailmsg = 1 etc.... and it worked. This is what is not making any sense to me. I have used this same script but with different var at least a dozen times in this program with no problem.
This is what the data looks like that I am sending to the script
print_r($_POST);
[emailmsg] => 1 [emailrt] => 2 [pid] => 6 [$emrtid] => 48 [$emmsid] => 46
This is one of the script that will not send the data to the database
$stmt = $db->prepare("UPDATE options SET pid = ?,emailmsg = ? WHERE id = ?");
echo $stmt->execute(array($_POST['pid'],$_POST['emailmsg'],$_POST['emmsid']));
$stmt = $db->prepare("UPDATE options SET pid = ?, emailrt = ? WHERE id = ?");
$stmt->execute(array($_POST['pid'],$_POST['emailrt'],$_POST['emrtid']));
I also tried it like this
$sql = "UPDATE options SET
pid = ?,
emailmsg = ?
WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->bindValue('1', $_POST['pid'], PDO::PARAM_INT);
$stmt->bindValue('2', $_POST['emailmsg'], PDO::PARAM_STR);
$stmt->bindValue('3', $_POST['emmsid'], PDO::PARAM_INT);
$stmt->execute();
$sql = "UPDATE options SET
pid = ?,
emailrt = ?
WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->bindValue('1', $_POST['pid'], PDO::PARAM_INT);
$stmt->bindValue('2', $_POST['emailrt'], PDO::PARAM_STR);
$stmt->bindValue('3', $_POST['emrtid'], PDO::PARAM_INT);
$stmt->execute();
If you literally copied your print_r output to your question, the problem is that your WHERE condition is never met so no row is ever updated.
This:
echo $stmt->execute(array($_POST['pid'],$_POST['emailmsg'],$_POST['emmsid']));
should be:
echo $stmt->execute(array($_POST['pid'],$_POST['emailmsg'],$_POST['$emmsid']));
// ^ that's what it looks like in your print_r
The same applies to $_POST['emrtid'] in your second query: $_POST['$emrtid'].
Try like using named parameter:
$stmt = $db->prepare("UPDATE options SET pid = :pid, emailrt = :emailrt WHERE id = :emrtid");
$stmt->execute(array('pid'=>$_POST['pid'],
'emailrt'=>$_POST['emailrt'],
'emrtid'=>$_POST['emrtid']
));

Categories