PHP和SQLite没有这样的文件或目录?

时间:2013-12-13 21:43:51

标签: php mysql database

我是数据库新手,我正在尝试登录页面检查数据库的用户名和密码。我收到了这个错误:

警告:mysqli_connect():( HY000 / 2002):第11行的/Applications/XAMPP/xamppfiles/htdocs/checklogin.php中没有此类文件或目录 无法连接

运行XAMPP,我尝试修改php.ini文件,并尝试连接到127.0.0.1而不是localhost。我不确定为什么会这样做。我的test.db文件应该在哪里?在与index.html相同的目录中?

<?php


$host="localhost"; // Host name 
$username="test"; // Mysql username 
$password="test"; // Mysql password 
$db_name="test"; // Database name 
$tbl_name="members"; // Table name 

// Connect to server and select databse.
mysqli_connect("$host", "$username", "$password")or die("cannot connect"); 
mysqli_select_db("$db_name")or die("cannot select DB");


// username and password sent from form 
$myusername=$_POST['myusername']; 
$mypassword=$_POST['mypassword']; 

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysqli_real_escape_string($myusername);
$mypassword = mysqli_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysqli_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword"); 
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>

这也有效吗?

 function getConnected($host,$username,$password,$db_name) 
 {
 $mysqli = new mysqli($host, $username, $password, $db_name);

 if($mysqli->connect_error) 
  die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());

 return $mysqli;
 }

 $mysqli = getConnected('localhost','user','password','database');

1 个答案:

答案 0 :(得分:0)

连接到SQLite

它看起来不像是连接到sqlite数据库,因为您尚未指定数据库文件的路径。尝试使用这个小脚本以更简洁的方式连接到数据库。

class Db {

    private $config;
    private $connection;

    public function __construct()
    {
        $this->config = array(
            'path' => 'path/to/your/database.sqlite'
        );

        $this->connect();
    }

    private function connect()
    {
        $connectionQuery = 'sqlite:' .$this->config['path'];

        try {
            $this->connection = new PDO($connectionQuery);
        } catch (PDOException $e) {
            echo $e->getMessage();
        }

        $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

    public function getConnection()
    {
        return $this->connection;
    }

}

$db = new DB();

数据库路径

将此'路径/更改为/ your / database.sqlite'到您喜欢的任何路径。

检索连接句柄

只需使用 $ db-&gt; getConnection()即可访问它。