PHP to access to a .db file - php

I am new to PHP and trying to create a search field that searches through my database file. I am putting my database file rc3.db inside the same folder that contains my PHP file and trying to connect it with mysqlite, however I
Tried $con = mysqli_connect("localhost:8888","user","password","rc3.db"); but errors,I don't have a user nor a password. Also tried $con = mysqli_connect(); it works but I'm not sure if which database it is connecting to. I also did the single arguement with rc3.db as below, but it is probably mistaking that for the hostname, which is the the first parameter that the method takes in.
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
<?php
//connection to the database
$con = mysqli_connect("rc3.db");
echo "Connected to MySQL<br>";
?>
</body>
</html>
Warning: mysqli_connect(): (HY000/2005): Unknown MySQL server host 'rc3.db' (22) in /Applications/MAMP/htdocs/searchform.php on line 9
Call Stack
# Time Memory Function Location
1 0.0005 229848 {main}( ) ../searchform.php:0
2 0.0005 230072 mysqli_connect ( ) ../searchform.php:9

As I understand your database is not a mysql db but a sqlLite database.
If that so, you can use the sample code bellow to access the data.
$db = new PDO('sqlite:rc3.db');
$query = $db->prepare("Your sql query here");
$query->execute();
while($row = $query->fetchObject())
{
//do your staff
}
Update 1
As #Sean pointed correctly in the comments as an alternative you can use sqlite_open
$con = sqlite_open('rc3.db', 0666, $error))

The connection to the database using the extension mysqli.
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));

use PDO like in code below. And read this https://renenyffenegger.ch/notes/development/web/php/snippets/sqlite/index
It really helped me
<?php
$db = new PDO("sqlite:tg.db"); // file tg.db in local folder
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $db -> query('SELECT * FROM tgdata'); // select all data from my table 'tgdata'
foreach ($query as $row) {
var_dump($row);
}

Related

Warning: mysql_connect(): Access denied for user

I am a beginner .
I copied a simple php page on the server web http://www.barman-team.ir/tt.php
and i import sql data base and make user & and pass on data base (in cpanel)
this page work on local host( xamp) but dont run on server
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body dir="rtl">
<?php
$link=mysql_connect("localhost","uname","pass");
mysql_select_db("barmante_ebram",$link);
$q="SELECT * FROM site_sug";//
$r=mysql_query($q,$link);
$line= mysql_fetch_array($r);
//while($line== $result->fetch_assoc()){
echo $line['site_suggestion_id'].$line['site_suggestion']."<br>";
//echo $row["site_suggestion_id"].$row["site_suggestion_name"].$row["site_suggestion_date"].$row["site_suggestion"]."<br>";
//}
?>
</body>
</html>
error log is:
Warning: mysql_connect(): Access denied for user 'barmante_ebram_u'#'localhost' (using password: YES) in /home/barmante/public_html/tt.php on line 11
Warning: mysql_select_db() expects parameter 2 to be resource, boolean given in /home/barmante/public_html/tt.php on line 12
Warning: mysql_query() expects parameter 2 to be resource, boolean given in /home/barmante/public_html/tt.php on line 14
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/barmante/public_html/tt.php on line 15
Use this kind of debugging to trace error.
I guess your all warning is related to USERNAME or PASSWARD. use correct username and password. and it will resolve problem.
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
Use mysql_error() with each query so that you will get to know what is causing problem ( useful for beginner )
The first error is saying that your password to the username your supplied meaning that it can't connect to your mysql and the other error are saying that you should have provide resource to the 2nd parameter. You just interchanged the sequence of the parameters. Use the code below
<?php
$link=mysql_connect("localhost","uname","pass");
mysql_select_db($link,"barmante_ebram");
$q="SELECT * FROM site_sug";//
$r=mysql_query($link);
$line= mysql_fetch_array($r);
//while($line== $result->fetch_assoc()){
echo $line['site_suggestion_id'].$line['site_suggestion']."<br>";
//echo $row["site_suggestion_id"].$row["site_suggestion_name"].$row["site_suggestion_date"].$row["site_suggestion"]."<br>";
//}
?>
Note*: Don't use mysql_* functions, it is deprecated . Use mysqli or PDO prepared statements
Hope this helps you
Assuming that you have correct permissions for the user, the following code should work. It will tell you whether you have error in connecting to the sql server, or there is any error in your query.
<?php
$db_hostname = 'localhost';
$db_database = 'barmante_ebram';
$db_username = 'uname';
$db_password = 'pass';
$db_link= new MySQLi($db_hostname, $db_username, $db_password, $db_database);
if(! $db_link) //if($db_link->connect_errno > 0)
die("Could not connect to database server\n" + $db_link->connect_error);
$query = "SELECT * FROM site_sug";
$result = $db_link->query($query);
if(!result)
die("Error in query".$db_link->error);
$row = $result->fetch_assoc();
echo $row['site_suggestion_id'].$line['site_suggestion'];
?>
Note: Please always do error checking (if( !successful) die(" ")). Your code does not have any. Its a good practice to follow.

Outputting contents of database mysqli

Hi I know this is a little general but its something I cant seem to work out by reading online.
Im trying to connnect to a database using php / mysqli using a wamp server and a database which is local host on php admin.
No matter what I try i keep getting the error Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given when i try to output the contents of the database.
the code im using is:
if (isset($_POST["submit"]))
{
$con = mysqli_connect("localhost");
if ($con == true)
{
echo "Database connection established";
}
else
{
die("Unable to connect to database");
}
$result = mysqli_query($con,"SELECT *");
while($row = mysqli_fetch_array($result))
{
echo $row['login'];
}
}
I will be good if you have a look at the standard mysqli_connect here
I will dont seem to see where you have selected any data base before attempting to dump it contents.
<?php
//set up basic connection :
$con = mysqli_connect("host","user","passw","db") or die("Error " . mysqli_error($con));
?>
Following this basic standard will also help you know where prob is.
you have to select from table . or mysqli dont know what table are you selecting from.
change this
$result = mysqli_query($con,"SELECT *");
to
$result = mysqli_query($con,"SELECT * FROM table_name ");
table_name is the name of your table
and your connection is tottally wrong.
use this
$con = mysqli_connect("hostname","username","password","database_name");
you have to learn here how to connect and use mysqli

mysql connection throughtout the session

I have a problem. Successfully made a login.php page that uses function:
db_connect();
to connect to MySQL database. Now I'm creating another page that would edit previous entries, but I can't access it with simple
db_edit(){... $result = mysqli_query($conn, $insert_query); ...}
because it says either:
"Warning: mysqli_query(): Couldn't fetch mysqli" or " Warning: mysqli_query() expects parameter 1 to be mysqli, null given"
It looks like the connection breaks when jumping to another page, and it should be reestablished from beginning like:
db_connect(); //again?
db_edit();
What is the proper way to pass database connection parameters from one session page to another? Should I pass $conn or $user and $pass? How do I do it?
You must include page of database connection to every page. Here you used db_connect() at one page but in second you didn't use it so you can not access MYSQLI from second page
Let take simple sample
database.php
<?php
// Here place code for database connection for mysqli
$con = mysqli_connect("localhost","root","pass"); //Localhost
if (!$con) {
die('Could not connect: ' . mysqli_error());
}
mysqli_select_db("testdb", $con);
?>
Page1.php
<?php
include_once("database.php");
...
$result = mysqli_query($con, $insert_query);
...
?>
Page2.php
<?php
include_once("database.php");
...
$result = mysqli_query($con, $insert_query);
...
?>
If you have more pages then you use include_once("database.php"); on each page.
here link can help you Click Here

PHP - Connect to Multiple MySQL Databases

So I have a PHP page that connects first to my database and does a bunch of stuff using the information from there. Now I want to connect to another database within the same PHP page and access data from there and insert the information into my original database.
The code:
<?php
session_start();
include ("account.php");
include ("connect.php");
....
do stuff here
....
include ("account2.php");
include ("connect2.php");
...
$thing = "SELECT abc, efg, hij FROM table ORDER BY RAND() LIMIT 1" ;
$thing = mysql_query($thing);
echo "$thing";
....
....
insert information into my database
(From account.php & connect.php files)
....
?>
Everything shows up except for $thing. It says, "Invalid query: Query was empty" but I know the query I used works because when I ran it in the account2 database, I got the results I wanted. Is there something wrong with my logic or is it something else?
You are not mentioning database connection link while executing the query. May be your second database connection is defined after the 1st one in connection.php file. So interpreter is considering 2nd connection while executing the query.
Define the connection link with query,
$thing = mysql_query($thing,$conn); //$conn is your mysql_connect
You can still use the mysql_connect or similar mysql_ functions (procedural way) But all these are now deprecated. You should use mysqli_ (mysql improved) functions or go with the object oriented way.
$conn1 = new mysqli(SERVER1,DB_USER1,DB_PASS1,DB1);
$conn2 = new mysqli(SERVER2,DB_USER2,DB_PASS2,DB2);
if($conn1 ->connect_errno > 0 || $conn2 ->connect_errno > 0){
die('Unable to connect to database server.');
}
Now while executing your query,
$query = "SELECT abc, efg, hij FROM table ORDER BY RAND() LIMIT 1";
$thing = $conn1 -> query($query); //if it's second connection query user $conn2
Many web applications benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.
For your case, i would make 2 persistent connections, store each in it's own variable and then use one whenever i need to. Check it out using the PDO class.
//Connection 1
$dbh1 = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
.
.
.
//Connection 2
$dbh2 = new PDO('mysql:host=localhost;dbname=test2', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
After you finish you first database operation, then you can close the connection using
mysql_close($c) //$c = connection
And again start for next database operation.
private static function _connectDB1()
{
//give hostname, dbusername, dbpassword
$con1 = mysql_connect("localhost", "root", "rootpass");
$db1 = mysql_select_db("dbone", $con1);
}
private static function _connectDB2()
{
//if you are using different db with different credentials
//you can give here like this
// mysql_connect("mynewhost", "mynewusername", "mynewpassword")
$con2 = mysql_connect("localhost", "root", "rootpass");
$db2 = mysql_select_db("dbtwo", $con2);
}

My php script is not using given username/pass/host rather using root#localhost (password: NO)

Got a problem! Though I found almost similar threads but none helped :(
I've written a php script to fetch the number of registered users from my MySQL database. The script is working great in my localhost; it is using the given username,pass and host name which are "root", "root", and "localhost" respectively, but the script is not using the given username/pass/host rather using root#localhost (password: NO) in Live server.
In the Live server I created a MySQL user, set an different password, and hostname there is of course not localhost. I updated the script with my newly created mysql users data. BUT, whenever I run the script, I see that the script is still using "root", "root", and "localhost"!!
take a look at the script:
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
$db = mysql_select_db ("regdb",$conn); //Oops, actually it was written this way in the script. I misstyped it previously. now edited as it is in the script.
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ");
while ($row = mysql_fetch_array($query)):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
-- Some says to change the default username and pass in the config.ini.php file located in phpMyAdmin directory. Would this help?? I didn't try this because either my hosting provider didn't give me privilege to access that directory (because I am using free hosting for testing scripts) or I simply didn't find it :(
Please help....
Foreword: The MySQL extension is marked as deprecated, better use mysqli or PDO
Though you store the connection resource in $conn you're not using it in your call to mysql_query() and you're not checking the return value of mysql_connect(), i.e. if the connection fails for some reason mysql_query() "is free" to establish a new default connection.
<?php
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
if ( !$conn ) {
die(mysql_error()); // or a more sophisticated error handling....
}
$db = mysql_select_db ("regdb", $conn);
if ( !$db ) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
while ( false!=($row=mysql_fetch_array($query)) ):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
edit: It looks like you're processing only one row.
Either move the echo line into the while-loop or (if you really only want one record) better say so in the sql statement and get rid of the loop, e.g.
// Query to fetch data
// make it "easier" for the MySQL server by limiting the result set to one record
$query = mysql_query("SELECT * FROM regd LIMIT 1", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
// fetch data and output
$row=mysql_fetch_array($query);
if ( !$row ) {
echo 'no record found';
}
else {
echo htmlspecialchars($row['total_regd']);
}
First of all:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
What is your mysql_error()? :)

Categories