Log in

View Full Version : check variables against array



AdrielGreene
07-14-2009, 12:47 AM
I'm having some trouble with a registration code check on my website. The members who sign up need to have a unique registration code which is stored in a mysql database. Getting the array looks something like this:


$q = "SELECT code FROM control";
$r = mysqli_query ($connect, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($connect));
$_control = mysqli_fetch_array ($r, MYSQLI_ASSOC);


Here is where I check against the code:


if ($_control['code'] == $_POST['code']) {
$reg = mail("myemail@email.net","new member","New member","New member");
} else {
echo '<p class="error">Please enter a valid registration code!</p>';
}

I'm guessing that the POST is only being checked against the first variable in the control array but I could very easily be simply confused. What do you think Dynamic Drive?

forum_amnesiac
07-14-2009, 07:05 AM
This is how I would do the query and then the if statatement


$r = mysql_query("SELECT code FROM control")
You can find the number of rows selected by
$num=mysql_num_rows($r);

You can then do a while loop


$x=0;
while ($x < $num) {

if (mysql_result($r,$x,'code') == $_POST['code']) {
$reg = mail("myemail@email.net","new member","New member","New member");
} else {
echo '<p class="error">Please enter a valid registration code!</p>';
}
$x++;
}

AdrielGreene
07-23-2009, 05:42 AM
I tried to adapt my code but nothing I've tried seems to work.

This is what my error checker see's
line 18: mysql_num_rows(): supplied argument is not a valid MySQL result resource


//create the registration code array
$q = "SELECT code FROM control";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
$_control = mysqli_fetch_row ($r);
$regnum = mysql_num_rows($r);


// Trim all the incoming data:
$trimmed = array_map('trim', $_POST);

//several lines of code

// Check for correct registration code:
$x = 0;
while ($x <= $regnum) {
if ($_control[$x] == $trimmed['code']) {$checkreg = 1;} //see if POST data equals a control array value
$x++;
}

if ($checkreg == 1) {
$reg = 1;
mail("myself@gmail.com","new practitioner","New Practitioner","New Practitioner");
} else {
echo '<p class="error">Please Enter a Valid Registration Code.</p>';
}

//several lines of code

if ($reg) { //rest of code

JasonDFR
07-26-2009, 07:21 AM
I think the better approach is to ask MySQL to return the row WHERE the unique registration code exists. If it exists in your db, you will get 1 row returned. If it does not exist, you will not get 1 row. Run the query after you get the unique code from the user.



$query = "SELECT * FROM `control` WHERE `code`='$code'";

$result = mysqli_query($link , $query);

if (mysqli_affected_rows($link) != 1) {

// Unique code does NOT exist
// Redirect to error page
exit;

}

// The rest of your code goes here.

Good luck.