How to fetch from MySql Database when using Include connection? - php

I'm using include connection file to connect to the database. My challenge is how do I fetch from the database this is where am stuck.
include 'connection.php';
$sql = 'SELECT * FROM country';
$results = mysqli_query($sql);

assume your connection.php contain
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
So the in your file, you're using include 'connection.php' to get the connection. By using include its act like single page now. Then you've to use it like below
require_once 'connection.php';
$sql= 'SELECT * FROM country';
$results = mysqli_query($con, $sql); # add connection string to query
Explanation
when you add this include 'connection.php'; then whatever the data on parent(connection.php) file (ex: variable, Functions, etc ..) will come to child.
Links to refer
In PHP, how does include() exactly work?
Are PHP include paths relative to the file or the calling code?
include, include_once, require or require_once?

Related

How to include variables inside a php file created via fopen

I am trying to create a php file with the fopen() function. The content of the php file(s) that will be created need to be built so that they can be executed at a later date to update a mysql db. So if the php file is created, it should show include to a config.php and a way to connect to the db and execute a query.
So for example, the file that will be created will look something like:
<?php
include_once 'config.php';
$updateSQL = "update table set is_active = 1 where id = 10";
$conn = mysqli_connect("$dbhost","$dbuser","$dbpass","$usedb");
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
} else {
mysqli_query($conn,$updateSQL );
}
?>
Creating an empty php file is simple but I don't know whether it is possible to show variables in the file that will be created.
FYI, the file will consist of other tasks such as creating a directory which I can do, this is the part I am stuck on so any suggestions?
this my solve your query
<?php
$text = "hi Amar";
$var_str = var_export($text, true);
echo $var = "\n\n\$text = $var_str;\n\n";
?>
Result: $text = 'hi Amar';

PHP to access to a .db file

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);
}

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

Variables from included php file

I currently have a php file with html code in it. At the beginning of the body tag im including a dbcon.php which contains a db connection, a query and a fetch_result. I now want to use those results later in the html file but i cant get it to work.
Website-file looks like this:
<html>
<head>...</head>
<body>
<?php include("dbcon.php"); ?>
...
<some html stuff>
...
<? here i want to use the data from the query ?>
...
</body></html>
The dbcon.php simply contains the connection, the query and the fetch_results.
edit:
dbcon:
<?php
$con=mysql_connect("localhost:8889","user","pw","db");
$result_query = mysql_query($con,"SELECT * FROM table");
$results = mysql_fetch_array($results_query);
?>
I cant access the data in the lower part of the html file.
Your code is "right", in that you don't need anything more to access your dbcon.php variables.
But you're mixing mysql_ and mysqli_ syntax :
mysql_query take as first parameter the query, not the connexion
mysqli_query take as first parameter the connexion, and the query as second one
You should use mysqli_ :
$con = mysqli_connect("localhost:8889","user","pw","db");
$result_query = mysqli_query($con, "SELECT * FROM table");
$results = mysqli_fetch_array($results_query);
Another version, object oriented :
$mysqli = new mysqli("localhost:8889", "user", "pw", "db");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$results = array();
if ($result_query = $mysqli->query("SELECT * FROM table")) {
$results = $result_query->fetch_array();
}
don't use mysql_ function,it is depricated.
anyway you use wrong variable name. $results_query in mysql_fetch_array($results_query) so change it to $result_query and it might work.
<?php
$con=mysql_connect("localhost:8889","user","pw","db");
$result_query = mysql_query("SELECT * FROM table");
$results = mysql_fetch_array($result_query );
?>

Include no database selected

I have a project (exisiting) and I am ordered to continue it
but there's something strange
in my connection
<?php
include "adodb5/adodb.inc.php";
$config['mysqlhost'] = 'localhost';
$config['mysqluser'] = 'xxx';
$config['mysqlpass'] = 'yyy';
$config['mysqldb'] = 'zzz';
$DB = ADONewConnection('mysql');
$DB->Connect($config['mysqlhost'],$config['mysqluser'],$config['mysqlpass'],$config['mysqldb'],true);
?>
and if I try to call query (same queries as below) from this page, it works (and when I echo, it shows the value)
So I go to other page
<?
include ("inc/con.php");
?>
<?php
$sql = ("SELECT * FROM table");
$query = mysql_query($sql)or die($myQuery."<br/><br/>".mysql_error());
$result = mysql_fetch_array($query);
echo $result ['table id'];
?>
and the result is
Notice: Undefined variable: myQuery in C:\xampp\htdocs\d88\www\mypage.php on line 9
No database selected
is there anything wrong with it?
since i try on con page, it works and when i include it to other page, it not working
You are not defining any $myQuery either in inc/con.php nor in the same file itself. Also you are not selecting any database with mysql_select_db:
mysql_select_db($config['mysqldb']);
You are suggest, also, not to use mysql_* functions as they are going to be deleted and are yet deprecated (and you can use PDO or mysqli).
Notice: I think $sql = ("SELECT * FROM table") gets evaluated as $sql = true.
You can not connect with ADODB connection and establish a query with mysql_query.
the syntax is something like this mysql_query ($query ,$con). $con is optional but if you do not specify it, the last link opened by mysql_connect() is assumed; but you have not any mysql_connect() statement before
because of my version of php, i must use <?php ?> instead of <? ?>
thanks for helping

Categories