我正在使用下面的代码来检查密码。当我输入表单的用户名在数据库中时,它工作正常。但如果用户名不可用,则 foreach 会抛出错误。
<?php
$u=$_REQUEST['loginname'];
$P=$_REQUEST['loginpass'];
$pas=md5($P);
$server="localhost:3306";
$user="root";
$pass="prabhs226";
$database="sugar";
$conn=mysqli_connect($server,$user,$pass);
mysqli_select_db($conn,$database);
$sql=("select b_pass from ub_per where b_id='$u' or b_email= '$u';");
$res = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($res,MYSQLI_ASSOC);
foreach($row as $value){
$value;}
if($value==$pas){
echo "password matched";
}
else{echo"not matched";}
?>
我收到这个错误:
PHP Warning: Invalid argument supplied for foreach() in E:\noname\name\logged.php on line 19 PHP Notice: Undefined variable: value in E:\noname\name\logged.php on line 22.
另外我想知道是否有任何方法可以为完整的网站定义一次数据库凭证。
最佳答案
我同意 Luthando Loot。此外,如果您只想为完整的网站定义一次数据库凭据。您可以使用凭据创建一个常量文件,并将其包含到您连接到数据库的函数文件中。之后,在您的脚本中包含连接功能。这样您就不必在每次需要数据库时都编写脚本来连接。只需包含它就可以了。
例子
常量.php
/**
* Database Constants - these constants are required
* in order for there to be a successful connection
* to the MySQL database. Make sure the information is
* correct.
*/
define("DB_SERVER", "localhost");
define("DB_USER", "User_db");//enter your database username
define("DB_PASS", 'Pass_db');//databse password
define("DB_NAME", "Name_db");//database name
数据库.php
/**
* Database.php
*
* The Database class is meant to simplify the task of accessing
* information from the website's database.
*/
include("constants.php");
try {
$db = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USER, DB_PASS); //Initiates connection
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Sets error mode
}
catch (PDOException $e) {
file_put_contents("log/dberror.log", "Date: " . date('M j Y - G:i:s') . " ---- Error: " . $e->getMessage() . PHP_EOL, FILE_APPEND);
die($e->getMessage()); // Log and display error in the event that there is an issue connecting
}
请记住这是一个 PDO 连接而不是 mysqli。这只是一个示例,说明如何使用常量以便将其用于整个站点。
关于返回空结果时的php mysql错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33228832/