user3367183
user3367183

Reputation: 35

PHP to SQL Insert not Working

I have a simple query that I'm using to insert a record based on a form submission, but it's not writing the record to the database. It's also not throwing an error. I used a var_dump and verified that the variables are posting correctly, so I think the issue is in the query syntax, but I've checked that too.

Any help or guidance is greatly appreciated. Here is the code:

if (isset($submit)){

$user_id = $_SESSION['user_id'];
$anthem1 = $_POST['anthem1'];
$cointoss2 = $_POST['cointoss2'];

$query = "INSERT INTO mypicks (";
$query .= "  user_id, anthem1, cointoss2";
$query .= ") VALUES (";
$query .= "  '{$user_id}', '{$anthem1}', '{$cointoss2}'";
$query .= ")";
$result = mysqli_query($connection, $query);

}

Upvotes: 0

Views: 58

Answers (1)

bmcculley
bmcculley

Reputation: 2088

You'll want to add some checks into your code.

First you'll want to make sure that your database connection is happening:

$connection = new mysqli('localhost', 'username', 'password', 'database');

if($connection->connect_errno > 0){
    die('Unable to connect to database [' . $connection->connect_error . ']');
}

Next thing, you'll want to make sure that your $submit variable is set, so your code block is actually firing.

If it is, make sure that your query is working:

$user_id = $_SESSION['user_id'];
$anthem1 = $_POST['anthem1'];
$cointoss2 = $_POST['cointoss2'];

$stmt = $connection->prepare("INSERT INTO mypicks ( user_id, anthem1, cointoss2 ) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $user_id, $anthem1, $cointoss2);
$stmt->execute();

if(!$result = $stmt->get_result()){
    die('There was an error running the query [' . $connection->error . ']');
}

Also don't forget to clean up after wards

$stmt->close();
$connection->close();

Upvotes: 1

Related Questions