PHP If语句不重定向空字符串
I have some code that is entering values into a database. I have an IF statement at the start to check if the string $jobno
is empty and if it is, it redirects back to the form. But its not redirecting just runs the code successfully.
if ($jobno=='') {
header( 'Location: add_job.php?error=1');
}
What am I doing wrong?!
<?php
$status=$_POST["status"];
$jobno=$_POST["jobno"];
$number=$_POST["number"];
$street=$_POST["street"];
$suburb=$_POST["suburb"];
$city=$_POST["city"];
$first_name=$_POST["first_name"];
$first_name = ucfirst($first_name);
$last_name=$_POST["last_name"];
$last_name = ucfirst($last_name);
$landline=$_POST["landline"];
$mobile=$_POST["mobile"];
$fax=$_POST["fax"];
$email=$_POST["email"];
if ($jobno=='') {
header( 'Location: add_job.php?error=1');
}
$con=mysqli_connect("server","user","pass","database");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to database: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO jobs (status, jobno, number, street, suburb, city, first_name, last_name, landline, mobile, fax, email)
VALUES ('$status', '$jobno', '$number', '$street', '$suburb', '$city', '$first_name', '$last_name', '$landline', '$mobile', '$fax', '$email')");
mysqli_close($con);
header( 'Location: photo_upload.php?new_job_success=y&jobno=' . $jobno ) ;
?>
It could be 2 things
- $jobno is not ''
- since you aren't returning after your redirect, and you are doing a second redirect a bit later, your header would look like:
- Location: add_job.php?error=1
- Location: photo_upload.php?new_job_success=y&jobno=
put an else
clause in your code:
<?php
...
if ($jobno=='') {
header( 'Location: add_job.php?error=1');
}
else {
$con=mysqli_connect("server","user","pass","database");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to database: " . mysqli_connect_error();
}
else
{
mysqli_query($con,"INSERT INTO jobs (status, jobno, number, street, suburb, city,first_name, last_name, landline, mobile, fax, email) VALUES ('$status', '$jobno', '$number', '$street', '$suburb', '$city', '$first_name', '$last_name', '$landline', '$mobile', '$fax', '$email')");
mysqli_close($con);
header( 'Location: photo_upload.php?new_job_success=y&jobno=' . $jobno ) ;
}
}
?>
try using this code:
if (!isset($_POST["jobno"])) {
header( 'Location: add_job.php?error=1');
}
<?php
^---this space
is OUTSIDE of your code, so it's output, which makes
header( 'Location: add_job.php?error=1');
cause a "headers already sent" error.
You are also wide open and begging for an SQL injection attack
There is an space in the starting which is causing this error. You can't echo any output before sending the headers not even a single space. This small space is causing the header already sent error.You should remove the space on the starting of the php file. Your code should look like this
<?php
$status=$_POST["status"];
I hope this helps you