PHP将数据插入mySQL两次而不是

时间:2016-01-08 08:35:05

标签: php mysql mysqli

<?php
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "test";

$name="admin";
$pass="passerino";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else {
  echo nl2br("Conected \n");
}
$sqlin="INSERT INTO data_test (username, password) VALUES ('valname','valpass')";
$result=$conn->query($sqlin);
if ($conn->query($sqlin) === TRUE) {
echo "New record created successfully";
} else {
 echo "Error: " . $sqlin . "<br>" . $conn->error;
 }
 $conn->close();
 include_once "read.php";
 ?>

您好我有这个简单的.php文件将数据插入到mySQL数据库中,但是它没有一次用一个请求执行两次。我怎么能停止这个?我使用的是wamp服务器x64,chrome,php 5.5.12 ; P.S read.php显示数据表

6 个答案:

答案 0 :(得分:3)

更改此代码

    $sqlin="INSERT INTO data_test (username, password) VALUES ('valname','valpass')";
    $result=$conn->query($sqlin);
    if ($conn->query($sqlin) === TRUE) {
    echo "New record created successfully";
    } else {
     echo "Error: " . $sqlin . "<br>" . $conn->error;
     }
     $conn->close();
     include_once "read.php";

$sqlin="INSERT INTO data_test (username, password) VALUES ('valname','valpass')";
$result=$conn->query($sqlin);
if ($result === TRUE) {
echo "New record created successfully";
} else {
 echo "Error: " . $sqlin . "<br>" . $conn->error;
 }
 $conn->close();
 include_once "read.php";

因为如果您运行此行$conn->query($sqlin);两次,它将运行您的查询两次并在数据库中插入记录两次

答案 1 :(得分:2)

因为您执行了查询时间

$result=$conn->query($sqlin);// first time
if ($conn->query($sqlin) === TRUE) {// second time

只执行一次

$sqlin="INSERT INTO data_test (username, password) VALUES ('valname','valpass')";
if ($conn->query($sqlin) === TRUE) {
echo "New record created successfully";
} else {
 echo "Error: " . $sqlin . "<br>" . $conn->error;
 }

不要直接插入值使用bind语句

http://php.net/manual/en/mysqli-stmt.bind-param.php

不要将普通密码存储到数据库读取密码哈希

http://php.net/manual/en/function.password-hash.php

http://php.net/manual/en/faq.passwords.php

答案 2 :(得分:0)

不要直接取结果变量,如下所示:

if ($conn->query($sqlin) === TRUE) {
echo "New record created successfully";
} else {
 echo "Error: " . $sqlin . "<br>" . $conn->error;
 }

答案 3 :(得分:0)

只需在if条件中使用变量

if($sqlin === TRUE)

答案 4 :(得分:0)

$conn->query($sqlin) === TRUE会导致双重使用$result === TRUE

答案 5 :(得分:0)

是的,这是一个很大的问题。你必须检查视图文件。这意味着,专注于您调用类的文件。你打了两次电话。如果您没有使用任何成功消息。它应该没问题,但是如果你使用它,那么请删除另一个电话。假设 -

示例:

$success_msg = "Data save successfully"; 

$save_blog_info = new Blog();
$success_msg = $save_blog_info->save_blog_info($_POST);

(来自主要公共职能部门)

您必须调用视图文件 -

$save_blog_info = new Blog();
$save_blog_info->save_blog_info($_POST);
$success_msg = $save_blog_info->save_blog_info($_POST);

不要使用 -

postgres --config-file=/usr/local/var/postgres/postgresql.conf -D /usr/local/var/postgres

感谢