Reputation: 145
the Invalid code message is showing when my page loads. Even though I haven't submit the html form. It should come out when I submit the invalid code through the html form. Any ideas how to solve this issue?
$db_selected = mysql_select_db("test", $con);
if (!$db_selected) {
die ('Database error!' . mysql_error());
}
else{
$row = mysql_query("SELECT * FROM discount_code WHERE disc_code IN('" .implode( "','", $dc_array )."')") or die(mysql_error());
if (mysql_num_rows($row) == 0){
echo 'Invalid code';
}
else{
echo 'success';
}
Upvotes: 1
Views: 946
Reputation: 76656
You can use isset()
to make sure the form was actually submitted.
Say your form is:
<form action="post" "somefile.php">
<input type="text" name="username" />
<input type="text" name="password" />
<input type="submit" name="yourSubmitFormButton" />
</form>
Then you can use the following:
if (isset($_POST['yourSubmitFormButton'])) {
// code goes here
}
So, when you load the page, the isset condition will evaluate to FALSE
and the code in the if
block will not get executed. When the submit button is pressed, the condition will evaluate to TRUE
and the subsqeuent statements will get executed.
Also, as it's currently written, your code is vulnerable to SQL injection. You should escape the user inputs before inserting them in your query.
$dc_array = mysql_real_escape_string($dc_array);
//code
Better yet, stop using the deprecated mysql_*
functions and switch to PDO or MySQLi, and learn to use parameterized queries.
Upvotes: 1
Reputation: 9765
You should wrap your code with
if ($_SERVER['REQUEST_METHOD'] === 'POST') {}
to be sure that it will be executed only after sending post request (sending form).
Of course you should also use PDO
or mysqli
instead of mysql_*
and think about prepared statements
.
Upvotes: 2