PHP 使用变量从 MySQL 获取单个值

PHP get single value from MySQL with variable

我似乎无法通过 UserEmail

通过简单的查询从 table 的用户中找到 UserID

我有简单的功能可以假设 return UserID functions.php

function get_userID($UEml) 
{
// Check database connection
  if( ($DB instanceof MySQLi) == false) {
    return array(status => false, message => 'MySQL connection is invalid');
  }
  $qSQL = "SELECT UsID FROM Users WHERE UsEml=? LIMIT 1";
  $qSQL = $DB->prepare($qSQL);
  $UEml = $DB->real_escape_string($UEml);
  $qSQL->bind_param("s", $UEml);
  $qSQL->execute();
  $result = $qSQL->get_result();
  while ($row = $result->fetch_row()) {
    return $row[0];
  }
//  return $row[0];
  if($qSQL) {
    return array(status => true);
  }
  else {
    return array(status => false, message => 'Not Found');
  }
}

我从 php 脚本中调用它 检查-User.php

<?php
require_once("db-config.php");
include 'functions.php';
...
$UsID = get_userID("joe@example.com");
echo 'UserID: <span style="color: blue">'. $UsID ."</span>";
...
?>

db-config.php

<?php
// Two options for connecting to the database:

define('HOST_DIRECT', 'example.com'); // Standard connection
define('HOST_LOCAL', '127.0.0.1');    // Secure connection, slower performance

define('DB_HOST', HOST_DIRECT);         // Choose HOST_DIRECT or HOST_STUNNEL, depending on your application's requirements

define('DB_USER', 'dbUser');    // MySQL account username
define('DB_PASS', 'SecretPas');    // MySQL account password
define('DB_NAME', 'DBName');     // Name of database
 
// Connect to the database
$DB = new MySQLi(DB_HOST, DB_USER, DB_PASS, DB_NAME);

if ($DB->connect_error) {
  die("Connection failed: " . $DB->connect_error);
}
//echo "Connected successfully";
?>

我尝试了很多变体,但运气不佳,还检查了这里的许多类似帖子,但就是无法正常工作。 谢谢

这里有几个错误:

  • $DB 在函数中不可用
  • echo的说法是错误的

这是没有这 2 个错误的代码:

function get_userID($DB, $UEml) 
{
    // Check database connection
    if ( ($DB instanceof MySQLi) == false) {
        return array(status => false, message => 'MySQL connection is invalid');
    }

    $qSQL = "SELECT UsID FROM Users WHERE UsEml=? LIMIT 1";
    $qSQL = $DB->prepare($qSQL);
    $qSQL->bind_param("s", $UEml);
    $qSQL->execute();
    $result = $qSQL->get_result();
    while ($row = $result->fetch_row()) {
        return $row[0];
    }
    //  return $row[0];
    // I do not know why you wrote this code. If you get an user this code will not be executed
    if ($qSQL) {
        return array(status => true);
    } else {
        return array(status => false, message => 'Not Found');
    }
}

还有你的echo

// ...
$UsID = get_userID($DB, "joe@example.com");
echo "UserID: <span style=\"color: blue\">{$UsID}</span>";