簡體   English   中英

在PHP / MySQLi中獲得錯誤的結果

[英]Getting wrong result in PHP/MySQLi

我試圖將表單中的用戶名和年齡插入名為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() “返回成功SELECT查詢的結果集,或其他DML查詢或失敗時返回FALSE。” http://php.net/manual/en/mysqli-stmt.get-result.php

使用affected_rows() http://php.net/manual/en/mysqli.affected-rows.php

“返回受上一次INSERT,UPDATE,REPLACE或DELETE查詢影響的行數。”

您還應該通過更改以下內容來檢查查詢錯誤:

$stmt->execute();

至:

if(!$stmt->execute()){
   trigger_error("There was an error....".$con->error, E_USER_WARNING);
}

嘗試插入時是否有任何錯誤。

參考:

錯誤報告添加到文件的頂部,這將有助於查找錯誤。

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

// Then the rest of your code

旁注:顯示錯誤只能在分段中完成,而不能在生產中完成。

你不能在這里使用get_result()你可以使用lastInsertid() ,它會給你最后一個插入的id,你可以使用condition作為:

<?
$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!";   
}
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM