开发者

Limit number of entires inserted into DB, PHP/AJAX

开发者 https://www.devze.com 2023-03-17 00:14 出处:网络
im currently trying to build a function where users on my website can unter up too 3 different interests. My interests are inserted into the DB using AJAX, my scripts are below...

im currently trying to build a function where users on my website can unter up too 3 different interests. My interests are inserted into the DB using AJAX, my scripts are below...

Form:

<div id="insert_response"></div>
<form action="javascript:insert()" method="post">
<input name="useridint" type="hidden" id="useridint" value="<?php echo $usersClass->userID(); ?>"/>

AJAX:

function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}

var http = createObject();
/* -------------------------- */
/* INSERT */
/* -------------------------- */
/* Required: var nocache is a random number to add to request. This value solve an Internet Explorer cache issue */
var nocache = 0;
function insert() {
// Optional: Show a waiting message in the layer with ID login_response
document.getElementById('insert_response').innerHTML = "Just a second..."
// Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
var useridint= encodeURI(document.getElementById('useridint').value);
var interest = encodeURI(document.getElementById('interest').value);
// Set te random number to add to URL request
nocache = Math.random();
// Pass the login variables like URL variable
http.open('get', 'upd_interests.php?useridint= '+useridint+'&interest=' +interest+'&nocache = '+nocache);
http.onreadystatechange = insertReply;
http.send(null);
}
function insertReply() {
if(http.readyState == 4){ 
var response = http.开发者_StackOverflowresponseText;
// else if login is ok show a message: "Site added+ site URL".
document.getElementById('insert_response').innerHTML = response;
}
}

PHP:

<?php require 'config.inc.php'; ?>

<!-- Verify if user exists for login -->
<?php
if(isset($_GET['useridint']) && isset($_GET['interest'])){

$url= $_GET['useridint'];
$sitename= $_GET['interest'];

$insertSite_sql = "INSERT INTO user_interests (user_id, interest) VALUES('{$url}' , '{$sitename}')";
$insertSite= mysql_query($insertSite_sql) or die(mysql_error());

echo $sitename;
} else { 
echo 'Error! Please fill all fileds!';
}
?>

What im asking is, is it possible I can somehow only have 3 records in the database for each user? So once a user has entered 3 rows, he can no longer enter more? If so what would the best option be?

Thanks


In response to @Daniel suggestion i tried the following only its now not inserting...

$res = mysql_query("select count(*) as cnt from user_interests where user_id=$useridint")
while($r=mysql_fetch_array($res))
{
if($r["cnt"] < 3)
{
if(isset($_GET['useridint']) && isset($_GET['interest'])){

$url= $_GET['useridint'];
$sitename= $_GET['interest'];

$insertSite_sql = "INSERT INTO user_interests (user_id, interest) VALUES('{$url}' , '{$sitename}')";
$insertSite= mysql_query($insertSite_sql) or die(mysql_error());

echo $sitename;
} else { 
echo 'Error! Please fill all fileds!';
}
}
  else
{
 echo "you have 3 ";
}
}   


just run . Also it is good idea to escape user input. just in case a user decides his favorite site is ;drop databases--;

$res = mysql_query("select count(*) as cnt from user_interests where user_id=$useridint")
while($r=mysql_fetch_array($res))
{
  if($r["cnt"] < 3)
  {
     insert
  }
  else
  {
     error
  }
}


You should use a stored procedure on a trigger, wich will be faster (no additional query & fetching) and safer (no way to be bypassed by mistake) than any PHP control. Try this kind of code:

CREATE TRIGGER myTrigger ON user_interests
BEFORE INSERT AS

    DECLARE @rowcount tinyint
    SELECT @rowcount = (SELECT COUNT(*) FROM user_interests, inserted
                                                        WHERE user_id=:new.user_id

    IF @rowcount > 3
    BEGIN
         RAISERROR ('The maximum number of interests has been reached')
    END;

GO

I did not try the code, but that should pretty much fit your needs.


$insertSite_sql = "
    INSERT INTO user_interests (user_id, interest)
    SELECT '{$url}' , '{$sitename}'
    FROM (SELECT 1) AS dummy
    WHERE ( SELECT COUNT(*)
            FROM user_interests
            WHERE user_id = '{$url}'
          ) < 3
";

This can quite easily be modified so users have different limits on the interests that are allowed to save.

0

精彩评论

暂无评论...
验证码 换一张
取 消