Jump to content

Only allow database insert on certain condition


AdRock

Recommended Posts

I want to only allow an insert query to run if the '$userid' only occurs less than 3 times in the database.  I run a check to count the number of occurences of a specific userid but it reports 1 if i echo out the result.  I want to be able to stop users entering more than 3 records at a time.

 

	$result = mysql_query("SELECT COUNT(*) FROM carshare WHERE userid='".$userid."'") or die (mysql_error());

$numrows = mysql_num_rows($result);

if($numrows < 3) {
    //query to enter form data into database

    $query = "INSERT INTO carshare (userid, seats_available, start_street, start_postcode, start_lat, start_long, end_street, end_postcode, end_lat, end_long, depart_time) 
    	VALUES('$userid', '$seats', '$s_street', '$s_postcode', '$s_lat', '$s_long', '$e_street', '$e_postcode', '$e_lat', '$e_long', '$depart')";

    $sql = mysql_query($query);    	    

    //if the query didn't complete display error message
    if(!$sql) { 
    	echo "There has been an error adding your carshare. Please contact the webmaster via contact page."; 
	echo mysql_error();
    	    }
}
else {
    echo "<h2 class=\"errorhead\">Warning - You are only allowed to add 3 car shares!!</h2>";
}
    }

Link to comment
Share on other sites

the reason it echos out 1 for any row is that you are asking it to count the rows and tell you the answer, then you are asking how many rows it returned, obviously the answer is 1 the other way to do it is

<?php
$result = mysql_query("SELECT * FROM carshare WHERE userid='".$userid."'") or die (mysql_error());
$numrows = mysql_num_rows($result);
?>

 

or

 

<?php
$result = mysql_query("SELECT COUNT(*) AS numrow FROM carshare WHERE userid='".$userid."'") or die (mysql_error());
$row = mysql_fetch_row($result);
$numrows = $row['numrow'];
?>

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.