How to close Mysql connection [duplicate] - php

This question already has answers here:
PDO closing connection
(6 answers)
Closed 6 years ago.
This is mysql Connection code.
$db_host = "localhost";
$db_name = "propstor_image";
$db_user = "root";
$db_pass = "";
try{
$db_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}?>
When I try to Close mysql connection by using mysql_close($db_con); It shows following error
" mysql_close() expects parameter 1 to be resource, object given in C:\wamp\www\property\member\include\login.php on line 57" .Please can you help me how to close mysql connection.

For PDO
The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.
reference link : Link

You could try this:
<Connection variable>.Close();
Example:
conn.Close();
I hope this helps!

Related

Why is the Port number throwing an error in the Heroku Postgresql connection [duplicate]

This question already has answers here:
What is the difference between single-quoted and double-quoted strings in PHP?
(7 answers)
Closed 3 years ago.
I have this block of PHP code that is supposed to connect to a PostgreSQL database in heroku
Code Below:
function __construct() {
$host = 'hostname';
$user = 'username';
$password = 'password';
$dbname = 'db_name';
$port = '5432';
try{
$this->db = new PDO('pgsql:host=$host;dbname=$dbname;user=$user;port=$port;password=$password');
}
catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
}
The connection throws an arror as follows:
Connection failed: SQLSTATE[08006] [7] invalid port number: "$port"
Why do I get an invalid port number?
Everything seems okay when I connect via the heroku cli but the php doesn't seem to cooperate.
Please help me figure out what I may have overlooked.
Variables are only expanded in double quoted strings.
$this->db = new PDO("pgsql:host=$host;dbname=$dbname;user=$user;port=$port;password=$password");
It probably complains about $port specifically because it is trying to convert that one to an int before trying to make the connection. If it would have gotten that far it would also have complained about the hostname.

Why I'm not able to create a new database in MySQL using PDO? Is it necessary to have a database already present before creating a new one using PDO? [duplicate]

This question already has answers here:
Pdo connection without database name?
(4 answers)
Closed 5 years ago.
I've installed the latest available version of XAMPP Package on my machine running on Windows 10 Home Single Language Edition.
I'm learning PHP and MySQL.
So, first of all in order to create a new database I wrote following code :
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
}
catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();//Getting 'Notice : Undefined variable : sql' for this line
}
$conn = null;
?>
The database didn't get created and I received following error in output after running above file in a web browser :
Notice: Undefined variable: sql in prog_1.php on line 16
SQLSTATE[HY000] [1049] Unknown database 'mydb'
Can someone please help me by correcting my code, so that I can further start studying the database concepts in actual manner?
Is it necessary to have a database already present when accessing the same using PDO?
P.S. : The database titled 'mydb' is currently not present in MySQL RDBMS.
You're setting the DB name in your DSN connection string, and it looks like mydb doesn't exists.
Just remove that part from the DSN string and try again.
Your $conn = new PDO() fails because there isn't a database called myDB (SQLSTATE[HY000] [1049]). Because that line fails your try catch statement will evaluate to the catch part before it declares the $sql variable. So when you try to access the $sql variable in the catch part it does not exist and will throw an Undefined variable error.
You'll have to move the $sql above the $conn = new PDO() line to fix the undefined variable error. To fix the missing database error you'll have to create a database called myDB.
try {
$sql = "CREATE DATABASE myDBPDO"; // moved it here
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// (...)
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage(); // no undefined variable
}
To connect to the database without selecting a specific database you'll have to change your new PDO() DSN to this:
$conn = new PDO("mysql:host=$servername", $username, $password);
For more information please check this answer.

variable is not recognized when included, pdo and php [duplicate]

This question already has answers here:
Giving my function access to outside variable
(6 answers)
Closed 8 years ago.
I have a problem. I am including my database details in my functions.php file. Like this:
db.php:
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "root";
$dbc = new PDO("mysql:host=" . $dbhost . "; dbname=" . $dbname ."", $dbuser, $dbpass);
functions.php:
include_once 'db.php';
function retrieve($count)
{
$query = "SELECT * FROM table WHERE column = ?";
$sth = $dbc->prepare($query);
$sth->bindValue(1, $count);
$sth->execute();
$resultCount = $sth->rowCount();
}
file.php:
include 'functions.php';
...
When I try to call my functions file in file.php, so I can use the function retrieve, my php_error.log file shows the following:
[Date] PHP Notice: Undefined variable: dbc in functions.php on line 6
My goal is to create an instance of PDO and use that in all the other pages so I don't have to create an instance over, and over again. I tried to achieve this by creating the $dbc variable and instancing a new PDO connection to it in db.php. Then, I would include it in functions.php so whenever a function is called, the $sth variable will hold the methods used, using $dbc (the instance of the PDO connection).
Does anyone know why am I getting this error, and possibly, could anyone give me some advice on how to parametrize the creation of an instance of PDO and use it/them throughout other pages?
Thank you for your time and help!
Cheers!
You have to pass the database connection to the function where your query is in order for it to work.

Access denied for user ''#'localhost' (using password: NO) [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 4 years ago.
Attempting to connect to localhost sql db using the following code (Not doing anything with query at this point just want the query to execute):
<?php
$host = "localhost";
$port = 3306;
$socket = "";
$user = "root";
$password = "Password1";
$dbname = "CIIP_WIKI";
$con = new mysqli($host, $user, $password, $dbname, $port);
if(!$con)
{
echo ("db connection failed!");
die ('Could not connect to the database server' . mysqli_connect_error());
}
else {
echo ("db connection established.");
echo ("<br/>");
}
$query = sprintf("SELECT first_name FROM actor WHERE actor_id='1'");
$result = mysql_query($query);
$con->close();
?>
I keep getting the following...
Welcome
db connection established.
Warning: mysql_query(): Access denied for user ''#'localhost' (using password: NO) in C:\Program Files (x86)\EasyPHP-12.1\www\Cisco Wiki\index.php on line 31
Warning: mysql_query(): A link to the server could not be established in C:\Program Files (x86)\EasyPHP-12.1\www\Cisco Wiki\index.php on line 31
Why does this not work?
This is because you create a connection using mysqli_ and then use mysql_ to try to fetch your result. They are different API's.
<?php
/* You should enable error reporting for mysqli before attempting to make a connection */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
/* Set the desired charset after establishing a connection */
mysqli_set_charset($mysqli, 'utf8mb4');
printf("Success... %s\n", mysqli_get_host_info($mysqli));
Example taken from the PHP manual
This warning will be logged anytime you try to execute a query without a valid connection object being available.
In your case you thought you had a valid connection object available, but you created it using mysqli while your query is being executed using mysql. Those are two different APIs and so the mysql_query function was looking for a mysql connection object and didn't find it.

Warning: mysql_fetch_row() expects parameter 1 to be resource [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
mysql_fetch_array() expects parameter 1 to be resource, boolean given in select
I am receiving the below message when I run this script:
Warning: mysql_fetch_row() expects parameter 1 to be resource, string given in /var/www/html/toolkit/routing.php on line 12
I have ran the query in the mysql console and it prints the correct row. Not sure why I cant get it to show up in php?
routing.php page:
<?php
error_reporting(E_ALL);
////error_reporting(0);
ini_set('display_errors', 'On');
include("db/sbc_config.php");
include("db/mysql.class.php");
$db = new MySQL(true, DB_DATABASE_ROUTING, DB_SERVER, DB_USER , DB_PASS);
if ($db->Error()) $db->Kill();
$searchroute = "SELECT * FROM destination_route as d WHERE d.destPrefix='2146811'";
$result = mysql_fetch_row($searchroute);
echo $result;
?>
sbc_config.php:
<?php
//database server
define('DB_SERVER', "10.10.1.146");
//database login name"
define('DB_USER', "user");
//database login password
define('DB_PASS', "pasword");
//database names
define('DB_DATABASE_ROUTING', "routing");
//smart to define your table names also
define('TABLE_DESTINATION_ROUTE', "destination_route");
?>
mysql_fetch_row takes a cursor and returns the next row in that cursor. You're trying to give it a string. You're missing a step.
You'll have to execute that query first:
$cursor = mysql_query($searchroute); // for example
$result = mysql_fetch_row($cursor);
You have to execute the query before you can fetch results:
$searchroute = "SELECT * ...";
$results = mysql_query($searchroute);
$row = mysql_fetch_row($results);
mysql_fetch_row must be called after mysql_query, you can't pass the query into the fetch row
- see PHP Manual
$db = new MySQL(true, DB_DATABASE_ROUTING, DB_SERVER, DB_USER , DB_PASS);
is that supposedto be MySQLi? The mysql_*() functions do not have an OOP interface. You'd be mising mysqli and mysql calls, which is not supported. They're completely independent of each other internally, and a db handle or result statement from one is NOT useable in the other.

Categories