Reputation: 253
I have a PHP code that monitors my credits for our clients. If the client reaches 0 credits the php should not go to the desired page but to a page that will direct him to a notification page that he is low or has no credits
<script>
function validateForm()
{
var x=document.forms["lbs_trace"]["lbs_case"].value;
var y=document.forms["lbs_trace"]["lbs_reason"].value;
var count = 0;
if (!(x==null || x==""))
{
count++;
}
if (!(y==null || y==""))
{
count++;
}
if(count < 2){
alert("Please complete CASE / RA number and REASON for trace");
return false;
}
}
</script>
<?php
// Database Passwords
$host="localhost"; // Host name
$username="stingin_epanic"; // Mysql username
$password="*****"; // Mysql password
$db_name="*****"; // Database name
$tbl_name="TEST_credits"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$result = mysql_query("SELECT * FROM TEST_credits WHERE id='1'");
?>
<?php
$crds=0;
while($rows=mysql_fetch_array($result)){
?>
<span class="blue11" style="font-size: 12px"><span class="blue11" style="font-size:
12px"> </span>
<label for="credit"></label>
<input type="text" name="credit" value="<?php echo $rows['credits']; ?>" id="credit"
/>
<?php
if($rows['credits'] > 0)
{
$crds=1;
}
}
if($crds==0)
{
header("Location:../main.php");
}
?>
</span>
<form method="post" action="../lbs/lbs_record.php" name="lbs_trace" onsubmit="return
validateForm()">
I had it working great all I added was the validateForm() to make sure that the fields are completed. Previously I just posted the form and it worked. Could this be the reason?
Upvotes: 0
Views: 790
Reputation: 9775
Few things about your code.
When you want to get only one row, just use mysql_fetch_array()
. You don't need loop for that.
Don't use deprecated mysql_*
functions. Instead use PDO
or mysqli_*
.
You can't set new header using header()
function after sending anything to browser (so it have to be in first PHP block in your code). Move your JS to the bottom of file.
After using header()
with Location
you have to use die()
to stop executing script. In other case, PHP will execute some more lines before redirect (or all, depends on server configuration).
In header()
with Location
you should use absolute URL. Read about it in RFC 2616.
After executing query, don't put result to mysql_fetch_array()
. First check if everything is ok with it. In other case you'll miss error that could happen.
And the reason that your script is not working is lack of return true
in your JS validation function (at the end, when everything is checked). Without it browser will think that validation failed and will not send request.
Upvotes: 2