我在过程中使用 mysqli 语句 php..... 数据类型不起作用

i am using mysqli statement in procedural php..... data types dont work

列 test_int 是一个 integer 但是当我执行下面的查询时它显示成功。 我不知道它是如何成功的,因为我输入的是一个字符串 $id = "tett"; 我认为它不应该执行查询,因为数据类型不匹配。

<?php


include('db_connect.php');


// Prepare an insert statement
$sql = "INSERT INTO admin (test_int, username, password, maname) VALUES (?, ?, ?, ?)";

if($stmt = mysqli_prepare($con, $sql)){
    // Bind variables to the prepared statement as parameters
    mysqli_stmt_bind_param($stmt, "isss", $id, $username, $password, $maname);

    // Set parameters
    $id = "tett";
    $username = "New username";//$_REQUEST['first_name'];
    $password = "New password";//$_REQUEST['last_name'];
    $maname = "New Name";//$_REQUEST['email'];

    // Attempt to execute the prepared statement
    if(mysqli_stmt_execute($stmt)){
        echo "Records inserted successfully.";
    } else{
        echo "ERROR: Could not execute query: $sql. " . mysqli_error($con);
    }
} else{
    echo "ERROR: Could not prepare query: $sql. " . mysqli_error($con);
}

// Close statement
mysqli_stmt_close($stmt);

// Close connection
mysqli_close($con);

您在 bind_param 中指定的类型告诉 PHP 它应该将值转换为什么。 99.99% 的时间您应该将其转换为字符串,这样您就不会 运行 陷入问题。如果将其转换为整数 PHP will do the usual casting。由于 tett 无法转换为正确的数字,因此 PHP 只会将其转换为 0.

对了,大家一定要记得开启mysqli的报错功能。将此行放在 mysqli_connect() 之前:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

如果删除所有不必要的内容,您还可以使代码更简单。

<?php

include 'db_connect.php';

// Prepare an insert statement
$sql = "INSERT INTO admin (test_int, username, password, maname) VALUES (?, ?, ?, ?)";

$stmt = $con->prepare($sql);
// Bind variables to the prepared statement as parameters
$stmt->bind_param("ssss", $id, $username, $password, $maname);

// Set parameters
$id = "tett";
$username = "New username"; //$_REQUEST['first_name'];
$password = "New password"; //$_REQUEST['last_name'];
$maname = "New Name"; //$_REQUEST['email'];

// Attempt to execute the prepared statement
$stmt->execute();
echo "Records inserted successfully.";

切勿以明文形式存储密码或使用 MD5/SHA1! 仅存储使用 PHP 的 password_hash(), which you can then verify using password_verify(). Take a look at this post: and learn more about bcrypt & password hashing in PHP[=20 创建的密码哈希=]