简体   繁体   English

PHP至SQL插入无法正常工作

[英]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. 我使用了var_dump并验证了变量是否正确发布,因此我认为问题出在查询语法中,但我也对此进行了检查。

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);

}

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. 接下来,您需要确保已设置$submit变量,因此您的代码块实际上正在触发。

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM