Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP/MySQLi中得到错误的结果_Php_Mysqli - Fatal编程技术网

在PHP/MySQLi中得到错误的结果

在PHP/MySQLi中得到错误的结果,php,mysqli,Php,Mysqli,我正在尝试将表单中用户的姓名和年龄插入名为users的数据库中。成功插入后,我希望显示一条成功消息。这是我的代码,但即使插入成功,它也会以某种方式打印失败消息: <?php require_once('Connections/Localhost.php'); ?> <?php $success = NULL; if(isset($_POST['AddUser'])) { session_start(); $name = $_POST['Name'];

我正在尝试将表单中用户的姓名和年龄插入名为users的数据库中。成功插入后,我希望显示一条成功消息。这是我的代码,但即使插入成功,它也会以某种方式打印失败消息:

<?php require_once('Connections/Localhost.php'); ?>
<?php

$success = NULL;

if(isset($_POST['AddUser'])) {

    session_start();

    $name = $_POST['Name'];
    $age = $_POST['Age'];

    $stmt = $con->prepare("INSERT INTO employees(Name, Age)Values(?, ?)");

    $stmt->bind_param('ss', $name, $age);

    $stmt->execute();

    $result = $stmt->get_result();

    if($result) {

    $success = "Added Successfully!";   

    }
    else {

    $success = "Sorry! Couln't add!";   

    }

}

?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Add User</title>
<link href="Stylesheet/form.css" rel="stylesheet" type="text/css">
</head>

<body>
<div id="form">
<form action="index.php" id="form1" name="form1" method="POST">
  <div class="formfield"><input name="Name" type="text" id="Name" placeholder="Name"></input><br></div>
  <div class="formfield"><input name="Age" type="number" id="Age" placeholder="Age"></input><br></div>
  <div class="formbutton"><input name="AddUser" type="submit" id="AddUser" value="Add"></input></div>
</form>

<?php 

echo "<br>";
echo $success; 

?>
</div>
</body>
</html>


您不能使用
get_result()
这里您可以使用
lastInsertid()
,它将为您提供最后插入的id,然后您可以使用以下条件:

<?
$stmt = $con->prepare(" your query ... ");
$stmt->bind_param('ss', $name, $age);

$stmt->execute();
$lastId = $con->lastInsertId(); // add this 
if($lastId > 0) {
    $success = "Added Successfully!";   
}
else {
    $success = "Sorry! Couln't add!";   
}
?>
根据我的评论看到一个答案(如果没有删除,还有评论),我会将其作为答案提交:

get_result()
“对于成功的SELECT查询返回结果集,对于其他DML查询或失败返回FALSE。”

使用受影响的行()

返回受上次插入、更新、替换或删除查询影响的行数

您还应通过更改以下内容来检查查询中的错误:

$stmt->execute();
致:

如果在尝试执行插入时出现任何错误

参考:

添加到文件的顶部,这将有助于查找错误

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Then the rest of your code

get_result()
“对于成功的SELECT查询返回结果集,对于其他DML查询或失败返回FALSE。”-使用
impacted_rows()
“返回受上次插入、更新、替换或删除查询影响的行数。”
if($stmt->impacted_rows>0){$success=“Added Successfully!”;}else{$success=“对不起!无法添加!”}
错误在$result=$stmt->get_result()行中;
<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Then the rest of your code