This question already has answers here:
Error: file is encrypted or is not a database
(7 answers)
Closed 5 years ago.
I have an SQLite database and am trying to connect to it with PHP. This is what I'm using:
<?php
$dbconn = sqlite_open('combadd.sqlite');
if ($dbconn) {
$result = sqlite_query($dbconn, "SELECT * FROM combo_calcs WHERE options='easy'");
var_dump(sqlite_fetch_array($result, SQLITE_ASSOC));
} else {
print "Connection to database failed!\n";
}
?>
However, I get this error:
Warning: sqlite_open() [function.sqlite-open]: file is encrypted or is not a database in C:\xampp\htdocs\deepthi\combadd\combadd_db.php on line 4
Connection to database failed!
What's wrong and how can I fix it?
Try to use PDO instead of sqlite_open:
$dir = 'sqlite:/[YOUR-PATH]/combadd.sqlite';
$dbh = new PDO($dir) or die("cannot open the database");
$query = "SELECT * FROM combo_calcs WHERE options='easy'";
foreach ($dbh->query($query) as $row)
{
echo $row[0];
}
$dbh = null; //This is how you close a PDO connection
Connecting To Database
Following PHP code shows how to connect to an existing database. If database does not exist, then it will be created and finally a database object will be returned.
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('combadd.sqlite');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
?>
Now let's run above program to create our database test.db in the current directory. You can change your path as per your requirement. If database is successfully created then it will give following message:
Open database successfully
SELECT Operation
Following PHP program shows how we can fetch and display records
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('combadd.sqlite');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
$sql =<<<EOF
SELECT * FROM combo_calcs WHERE options='easy';
EOF;
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "ID = ". $row['ID'] . "\n";
}
echo "Operation done successfully\n";
$db->close();
?>
<?php
if ($db = sqlite_open('sampleDB', 0666, $sqliteerror) ) {
$result = sqlite_query($db, 'select bar from foo');
var_dump(sqlite_fetch_array($result) );
} else {
die($sqliteerror);
}
?>
Make sure sqlite support is enable, check phpinfo()
One another solution to your problem is:
Using sqlite3 module instead
class DB extends SQLite3
{
function __construct( $file )
{
$this->open( $file );
}
}
$db = new DB( 'sampleDB.sqlite' );
Related
This question already has answers here:
Call to a member function prepare() on a non-object PHP Help [duplicate]
(8 answers)
Closed 2 years ago.
I can't seem to get simple query working to find UserID from the table of Users by UserEmail
I have simple function to suppose to 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');
}
}
and I call it from php script
check-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";
?>
I tried many variations, but no luck and also checked many similar posts here, but just can't get it working.
Thanks
You have a couple of errors here:
$DB is not available in the function
the echo statement is wrong
This is the code without these 2 errors:
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');
}
}
And your echo:
// ...
$UsID = get_userID($DB, "joe#example.com");
echo "UserID: <span style=\"color: blue\">{$UsID}</span>";
I ran var_dump(function_exists('mysqli_connect')); and it returned boolean true.
I am running the following code
<?php
$connect=mysqli_connect("localhost","root","root","dbname") or die("Unable to Connect");
$showtablequery="SHOW TABLES FROM dbname";
$query_result=mysqli_query($showtablequery);
while($showtablerow = mysqli_fetch_array($query_result))
{
echo $showtablerow[0]." ";
}
?>
It did not do anything. It did not print anything on the result webpage.
When I use mysql functions instead then it works fine.
What do I need to do to use mysqli function?
Oop
<?php
$mysqli = new mysqli("localhost","root","root","dbname") or die("Unable to Connect");
$showtablequery="SHOW TABLES FROM dbname";
$query_result=$mysqli->query($showtablequery);
while($showtablerow = $mysqli->fetch_array($query_result))
{
echo $showtablerow[0]." ";
}
?>
Even if you connected successfully, it cannot query the database without connection informatiokn.
Procedural
<?php
$connect=mysqli_connect("localhost","root","root","dbname") or die("Unable to Connect");
$showtablequery="SHOW TABLES FROM dbname";
$query_result=mysqli_query($connect, $showtablequery);
while($showtablerow = mysqli_fetch_array($query_result))
{
echo $showtablerow[0]." ";
}
?>
Instead of
$query_result=mysqli_query($showtablequery);
use
$query_result=$connect->query($showtablequery);
and instead of
$showtablerow = mysqli_fetch_array($query_result);
use
$showtablerow = $query_result->fetch_array();
I am trying to print out all of my records from my MYSQL database, but it is only disaplying the first record.
<?php
class database {
private $objDbConn;
function __construct($db_login_info){
$this->objDbConn = new mysqli($db_login_info['host'], $db_login_info['username'],
$db_login_info['password'], $db_login_info['database']);
if (mysqli_connect_errno()) {
die("Database connection failed". mysqli_connect_error());
}
}
function getBlogPosts(){
$objRes = mysqli_query($this->objDbConn, "SELECT * FROM blog_posts");
if(mysqli_errno($this->objDbConn)) {
die("Failed query: $strSql". $this->objDbConn->error);
}
while ($row = mysqli_fetch_array($objRes)) {
return $row['title']."<br>";
};
}
}
?>
The query works fine in PHPmyadmin as per below:
Because you use return, it exits the function with only the string of the first row. Append the text in the while loop to a variable, and return that variable after the while loop.
$allrows="";
while ($row = mysqli_fetch_array($objRes)) {
$allrows.=$row['title']."<br>\n";
};
return $allrows;
Heres my code. Simple.
<?php
echo 'start<br>';
//Do the conntection
$checkconnection = mysql_connect('localhost', 'root', 'rootpass');
//Check if it's valid
if(!$checkconnection) {
echo 'CheckFailed';
} else{
echo 'CheckSucess';
}
echo 'end'; ?>
but I only can see 'start'. There is no 'CheckFailed', 'CheckSucess', 'end'
What should I do?
I already install mysql, create database, create tables, of course.
<?php
// Create connection
$con=mysqli_connect("localhost","root","root","database");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return false;
}
$result = mysqli_query($con, "SELECT * FROM table;");
?>
my php version is 5.2, which is the old verison.
it is because i use the free server
it is my website http://driverrecord.hostzi.com/android_login_api/include/profile.php?username=4
i hope someone can help me. the problem may be about the code.
the error message:
Warning: mysql_query() [function.mysql-query]: Access denied for user 'a6578726'#'localhost' (using password: NO) in /home/a6578726/public_html/android_login_api/include/profile.php on line 20
profile.php
// array for JSON response
$response = array();
// include db connect class
require_once dirname(__FILE__). '/DB_Connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["username"])) {
$username = $_GET['username'];
// get a product from products table
$result = mysql_query("SELECT * FROM user WHERE user_id = $username");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$username = array();
$username["username"] = $result["user_id"];
$username["first_name"] = $result["first_name"];
$username["last_name"] = $result["last_name"];
$username["email"] = $result["email"];
$username["tel"] = $result["tel"];
$username["age"] = $result["age"];
$username["gender"] = $result["gender"];
// success
$response["success"] = 1;
// user node
$response["username"] = array();
array_push($response["username"], $username);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
DB_Connect.php
class DB_Connect {
// constructor
function __construct() {
}
// destructor
function __destruct() {
// $this->close();
}
// Connecting to database
public function connect() {
require_once 'include/config.php';
// connecting to mysql
$con = mysql_connect("XXXXXwebhost.com", "a6578726_driver", "abcde");
// selecting database
mysql_select_db(DB_DATABASE);
// return database handler
return $con;
}
// Closing database connection
public function close() {
mysql_close();
}
}
?>
config.php
<?php
/**
* Database config variables
*/
define("DB_HOST", "XXXXwebhost.com");
define("DB_USER", "a6578726_driver");
define("DB_PASSWORD", "abcde");
define("DB_DATABASE", "a6578726_driver");
?>
Creating a DB_Connect object is not sufficient to connect to the database. Call connect() on that object to connect to the database.
You are never connecting to the database. You are constructing a DB_Connect instance, but the code in DB_Connect::connect is never called. As such, when you run mysql_query, there is no active connection. If there's no active connection, mysql_query will try to establish a connection with some default usernames and passwords it scrapes together from behind the sofa or wherever, which obviously fails.