Page 1 of 1
header function in if statement
Posted: Sun Aug 10, 2008 8:39 am
by sketteksalfa
Im a beginner and maybe someone could help me on this. What happens here is that it is always does the first header statement and not the else statement if the argument is false. So it is always index.php that was opened and not student.php. What i wanted to do is verify first if the student id exist from the database then go to appropriate pages after verification.
<?php
$con = mysql_connect("localhost","rye","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("student", $con);
$result = mysql_query("SELECT * FROM student_info
WHERE student_id==$_POST[studid]");
if (student_id==$_POST[studid]) {
header ('location: index.php');
else
header ('locaton: student.php');
}
?>
Re: header function in if statement
Posted: Sun Aug 10, 2008 9:13 am
by Apollo
Several mistakes:
1. Use a single = in SQL queries to compare values, not == like in PHP code.
2. The result from your query does not get magically copied to the $student_id variable. You have to use $result to extract the data you want. See
mysql_num_rows and the
mysql_fetch_* functions.
(Actually, in this particular case, just mysql_num_rows would do since you're only checking the existence of a student id and not using any actual data)
3. You forgot to put a $ in front of student_id. Without it, php actually interpretes that as an unquoted string, so in fact you were always evaluating
if ("student_id"==$_POST[studid]) with your current code.
4. You forgot to quote studid. This is a key in an array, so it should be: $_POST['studid']
(similarly, php again treated this as a string, so in this case it accidentally worked all right, but it's bad practice)
5. What do you think what would happen if some smartass filled in
0; DELETE * FROM student_info as his id?
NEVER insert anything that comes from users directly in SQL queries. Instead, do
$s = mysql_real_escape_string($_POST['studid']); and then use
WHERE student_id='$s' in your query.
Re: header function in if statement
Posted: Sun Aug 10, 2008 2:10 pm
by desmi
+ You need brackets after the if ends and when else begins..
Code: Select all
if (student_id==$_POST[studid]) { //after student_id fixed to $student_id and studid fixed to 'studid'
header ('location: index.php');
//here should be }
else //here should be {
header ('locaton: student.php');
}
Re: header function in if statement
Posted: Mon Aug 11, 2008 11:19 pm
by sketteksalfa
thanks for the prompt response. let me try this out.