I have a pretty standard MySQL insert into statement that doesn't seem to be working. I'm posting an HTML form to this page and it's translating the information and inserting into the table (pending_jobs). It worked the first time and hasn't worked since. I'm not looking to UPDATE the row but add a brand new one every time this code is submitted so I figured this would be pretty simple. Here's the code:
<?php
include('includes/connect.php');
$id=$mysqli->real_escape_string($_POST['id']);
$sql = "SELECT * FROM users WHERE id='$id'";
$result = $mysqli->query($sql);
$row = mysqli_fetch_array($result);
$user_id = $_SESSION['user_id'];
$company_name = $row['company_name'];
$date_registered = $row['date_registered'];
$job_title=$mysqli->real_escape_string($_POST['jobtitle']);
$job_description=$mysqli->real_escape_string($_POST['jobdescription']);
$salary=$mysqli->real_escape_string($_POST['salary']);
$industry_sector=$mysqli->real_escape_string($_POST['industry']);
$number_people=$mysqli->real_escape_string($_POST['num_people']);
if(isset($_POST['payment']) && $_POST['payment']=='yes'){
$payment_received = 'Yes';
}
else{
$payment_received = 'No';
}
$sql_add = "INSERT INTO pending_jobs (company_name, job_title) VALUES ('$company_name', '$job_title')";
$result_add = $mysqli->query($sql_add);
if(isset($result_add)){
session_start();
$id = $row['id'];
$_SESSION['user_id'] = $user_id;
header('location:profile.php?id='.$id);
} else {
echo "<script>alert('".$job_title."');</script>";
}
?>
It is redirecting to the profile.php page so I know that $result_add is actually going through but when I check the table in the database there is no new row. Any ideas on why it wouldn't be creating a new row?
Change your query
to
$result_add = $mysqli->query($sql_add) or die($mysqli->error);
and you will see the problem at once. Also
if (isset($result_add)) {
will always be true, because $result_add
will be either true
or false
for your insert.
Unique columns or indexes could prevent this insert statement. Simply test the same insert in phpmyadmin, or the mysql console. Also, isset() will be true even if $result_add is false :)
try to return the error in case the statement fails, so you know what's wrong.
$sql = "SELECT * FROM users WHERE id='$id'";
$result = $mysqli->query($sql) or die("cannot select from users");
$result_add = $mysqli->query($sql_add) or die("cannot insert");
( some propose or trigger_error(mysqli->error.$result_add);
but I haven't tested this).
replace `if(isset($result_add)){` with `if($result_add){
The suggestion to look at the table is also a nice one.