【发布时间】:2017-03-20 16:33:30
【问题描述】:
我希望精通PHP的人可以帮助我解决我真的不明白的问题。
我有 2 个脚本。 1:test.php 2:functions.php。
我创建了一个小测试,我在 functions.php frim test.php 中调用了一个函数,它工作正常。我得到了回报,正如预期的那样。我还有第三个脚本 register.php,我可以在其中查询数据库并且工作正常。
所以我希望查询作为函数在functions.php中编写
问题:它似乎不会进行数据库查询!但是有一个连接
如果我将完全相同的查询移至 test.php,它会起作用!这有什么特殊的原因吗?我退出了 php 新手,但对 Java、C、JavaScript、Python 略知一二。
我已检查我的 include / require 是否正常。
1:test.php:
<?php
require 'includes/functions.php';
$name = 'testuser';
$_ok = 0;
$_ok = check_username ($name);
printf ( 'Navn i database?: ' . $_ok . '<br>' );
?>
2:functions.php:
<?php
require 'includes/db_connect.php';
// Check connection
if (! $mysqli) {
die ( 'mysqli_init_failed' );
}
if (mysqli_connect_errno ()) {
die ( 'Failed to connect to the Database, Sorry..! errorcode: ' .
mysqli_connect_errno() . ' <br>' . 'Error Type: ' . mysqli_connect_error () );
}
if ($debug_mode_c) {
print ('Connection Established: ' . mysqli_get_host_info ( $mysqli ) . '<br>') ;
print ('session_id: ' . session_id ()) . '<br>';
}
// 将 HTML-Header 设置为 utf-8。 header ( '内容类型: text/html; charset=UTF-8' );
// Functions
function check_username($_ok) {
$name = 'testuser';
$prep_stmt = "SELECT username FROM customs WHERE username=? LIMIT 1 ";
$stmt = mysqli_prepare($mysqli, $prep_stmt);
mysqli_stmt_bind_param($stmt, 's', $name);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $name_db);
mysqli_stmt_fetch($stmt);
if ($name == $name_db) {
echo "hello";
mysqli_close ($stmt);
$_ok = 0;
} else {
$name = '';
$_ok = 2;
}
mysqli_free_result($stmt);
mysqli_close($stmt);
return $_ok;
}
【问题讨论】:
-
我真的希望你在原始来源中有一些实际的缩进。这真的很难读。
-
在哪里打开数据库的
mysqli连接? -
Thermis Beris:我将在另一个脚本“includes/db_connect”中执行此操作我知道连接有效,并且我知道用户存在于数据库中。当它在 test.php 中时,所有代码都在工作。仅当移至functions.php 并调用该函数时,才不会进行任何查询。 ? :-(
-
@RAJensen 您确定您的连接按预期工作吗?尝试在
check_username上打开连接。如果这不起作用var_dump你的陈述就像这个var_dump($stmt)。如果你从转储中得到bool(false),那么你的查询就有错误! -
@Themis Beris:在 check_username 上打开连接没有帮助。 var_dump($stmt) 在使用 check_username() 时返回 NULL,但在 test.php 中执行时它工作正常。无法弄清楚为什么查询在 test.php 而不是在 functions.php 中有效。就像 php-server 在functions.php 中不执行数据库查询行一样。想知道查询是否只有在脚本中才被执行,即由浏览器调用,并且由于某种原因,如果它在“include / include_once / require” - php.script 中被调用,它将不起作用?