提问人:DenisZ 提问时间:2/1/2021 最后编辑:DenisZ 更新时间:2/1/2021 访问量:77
PHP使用变量[duplicate]从MySQL获取单个值
PHP get single value from MySQL with variable [duplicate]
问:
我似乎无法通过简单的查询从用户电子邮件的用户表中查找用户ID
我有一个简单的函数来假设返回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脚本check-User.php调用它
<?php
require_once("db-config.php");
include 'functions.php';
...
$UsID = get_userID("[email protected]");
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";
?>
我尝试了很多变体,但没有运气,还在这里检查了许多类似的帖子,但就是无法让它工作。 谢谢
答:
1赞
Giacomo M
2/1/2021
#1
这里有几个错误:
- $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, "[email protected]");
echo "UserID: <span style=\"color: blue\">{$UsID}</span>";
评论
0赞
DenisZ
2/1/2021
它不适用于全局$DB,会破坏脚本
0赞
Giacomo M
2/1/2021
@Dharman当然可以做到。您的选择
0赞
Giacomo M
2/1/2021
@Denis您确定 PHP 文件中$DB变量可用?
评论
$DB
在函数中不可用。$DB