如果代码在数据库中,我需要它来生成一个随机数


If the code is in the database I need it to generate a random number

require("inc/connection.php");
if ($link->connect_error)
    die('Connect Error: '.$link->connect_errno.': '.$link->connect_error);
$insertedcode = $_POST['code'];
$results = $link->query("SELECT code FROM code WHERE code = :code");
$query_params = array( 
    ':code' => $_POST['code']
);
$stmt = $link->prepare($results);
$result = $stmt->execute($query_params);
$row = $stmt->fetch();
if($row) {
    $number = mt_rand(0,3999);
    echo $number;
}

这就是我所拥有的,我认为我有随机数部分。但是由于某种原因,它给了我这个错误:

致命错误:在 C:''wamp''www''RoLuck''dashboard.php 在第 21 行

它不会执行,我不知道为什么。

你应该将 SQL 字符串传递给 prepare ,因此执行query调用是没有用的:

// skip next line
//$results = $link->query("SELECT code FROM code WHERE code = :code");
$query_params = array( 
    ':code' => $_POST['code']
);
// Use SQL as argument here, not $results
$stmt = $link->prepare("SELECT code FROM code WHERE code = :code");

您在使用 mysqli 的代码上以错误的顺序执行此操作,对吗?如果您在没有为代码分配实际参数的情况下进行查询,这就是原因。在查询之前准备查询,而不是之后。

 require("inc/connection.php");
    if ($link->connect_error)
        die('Connect Error: '.$link->connect_errno.': '.$link->connect_error);
    $insertedcode = $_POST['code'];
    //$results = $link->query("SELECT code FROM code WHERE code = :code");
    $query_string = "SELECT code FROM code WHERE code = :code";
    $query_params = array( 
        ':code' => $_POST['code']
    );
    $stmt = $link->prepare($query_string);
    $stmt->bind_param('s', $query_params[':code']);
    $result = $stmt->execute(); //$query_params is only in procedural, read the manual
    $row = $stmt->fetch();
    if($row) {
        $number = mt_rand(0,3999);
        echo $number;
    }