Two things I can think of top my head;
mysql_
has been deprecated, thus the else
kicks in.
- Your syntax maybe wrong for
mysql_query
?
Nonetheless, start over and start over with code that is functional and up-to-date...
Given that your connection is working properly update it to a new mysqli
syntax, it's very simple and much more elegant:
$connect = new mysqli( 'localhost', 'USERNAME', 'PASSWORD', 'DATABASE' );
// check for an error
if ($this->_connection->connect_error)
{
trigger_error("Connection Error: " . $this->_connection->connect_error(), E_USER_ERROR);
}
Now that you are connected walk-through a new process for your code.
Start by checking like you currently are for a submit
$_POST
so that you can start running the script:
if ( isset( $_POST['submit'] ) )
{
// Encode the URL when creating the variables
$name = htmlentities( $_POST['name'] );
$phone = htmlentities( $_POST['phone'] );
$cash = htmlentities( $_POST['cash'] );
$date = date( 'l jS \of F Y h:i:s A' );
// create sql
// DO NOT INSERT VALUES STRAIGHT INTO YOUR QUERY
$sql = "INSERT INTO tbl2 ( name, phone, cash, date ) VALUES ( ?, ?, ?, ? )";
Note: before continuing, let me explain that you should never insert content into your query because that would throw raw user input in the mist of your code. Now, most users will never try anything fishy. But anyone could easily throw a few SQL commands inside of your inputs and DELETE
, SELECT
, and UPDATE
your database content and cause numerous problems.
Here is some reference: https://en.wikipedia.org/wiki/SQL_injection
To work around that problem, use prepared statements. You can read all about it on PHP manual; and also see some real-life examples.
// prepare query
// USE PREPARED STATEMENTS
if ($stmt = $connect->prepare( $sql ))
{
// bind the params
$stmt->bind_param('ssss', $name, $phone, $cash, $date);
// execute the query
$stmt->execute();
// check for errors
if ($stmt->errno)
{
$message = array(
'is_error' => 'danger',
'message' => 'Error: ' . $stmt->error
);
}
// make sure at least 1 or more rows were affected
if ($stmt->affected_rows > 0)
{
$message = array(
'is_error' => 'success',
'message' => 'Success: ' . $stmt->affected_rows . ' rows were inserted.' // value should be 1
);
}
else
{
// if not, send warning to user
$message = array(
'is_error' => 'warning',
'message' => 'Warning: ' . $stmt->affected_rows . ' rows were updated.'
);
}
// close your connection
$stmt->close();
}
else
{
$message = array(
'is_error' => 'danger',
'message' => 'QUERY: error. Try again.'
);
exit;
}
}
else
{
$message = array(
'is_error' => 'warning',
'message' => 'There was no submission attempt. Try again.'
);
exit;
}
Notice in the code is broken down into parts where you can catch multiple errors, and it's important for debugging; it will allow you to know exactly where the code went wrong, and localize your problem to a single section of it.