为了账号安全,请及时绑定邮箱和手机立即绑定

PHP sql查询未向前端返回正确的行数

PHP sql查询未向前端返回正确的行数

PHP
大话西游666 2021-09-05 20:11:43
我正在尝试创建一个网站,其中 php 与后端 sql 连接。有 1 行用户名 = 'user1'。然而,这个简单的 PHP 代码来获取“user1”的详细信息 -<?php    /* Database credentials. Assuming you are running MySQL    server with default setting (user 'root' with password 'root') */    define('DB_SERVER', 'localhost');    define('DB_USERNAME', 'root');    define('DB_PASSWORD', 'root');    define('DB_NAME', 'startup');    /* Attempt to connect to MySQL database */    $conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);    // Check connection    if($conn === false){        die("ERROR: Could not connect. " . mysqli_connect_error());    }    echo '<p>Connected successfully</p>';    $sql = "SELECT id, username, password FROM users WHERE username = ?";    $stmt = mysqli_prepare($link, $sql);    $param_username = "user1";    mysqli_stmt_bind_param($stmt, "s", $param_username);    mysqli_stmt_execute($stmt);    // mysqli_stmt_store_result($stmt);    echo '<p>done</p>';    $val = mysqli_stmt_num_rows($stmt);    printf("%%d = '%d'\n", $val); // standard integer representation?>上面的代码返回这个输出 -$val 的值为 0,显然有 1 行用户名 = 'user1'。请帮忙,我需要在我的 php 脚本中获取“user1”的详细信息。
查看完整描述

2 回答

?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

您需要在任何地方正确使用连接变量名称。(在$conn您的情况下,它是,但您使用了$link)


<?php

    /* Database credentials. Assuming you are running MySQL

    server with default setting (user 'root' with password 'root') */

    define('DB_SERVER', 'localhost');

    define('DB_USERNAME', 'root');

    define('DB_PASSWORD', 'root');

    define('DB_NAME', 'startup');


    $conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);


    /* check connection */

    if (!$conn) {

        printf("Connect failed: %s\n", mysqli_connect_error());

        exit();

    }

    $param_username = "user1";

    $stmt = mysqli_prepare($conn, "SELECT id, username, password FROM users WHERE `username` = ?");

    mysqli_stmt_bind_param($stmt, "s", $param_username);


    /* execute prepared statement */

    mysqli_stmt_execute($stmt);


    printf("%d Row inserted.\n", mysqli_num_rows($stmt));


    /* close statement and connection */

    mysqli_stmt_close($stmt);


    /* close connection */

    mysqli_close($conn);

?>


查看完整回答
反对 回复 2021-09-05
?
慕婉清6462132

TA贡献1804条经验 获得超2个赞

你做错了什么,请更新并尝试


$sql = "SELECT id, username, password FROM users WHERE username = ?";

$stmt = mysqli_prepare($link, $sql);

$param_username = "user1";

mysqli_stmt_bind_param($stmt, "s", $param_username);

mysqli_stmt_execute($stmt);


查看完整回答
反对 回复 2021-09-05
  • 2 回答
  • 0 关注
  • 151 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信