MySQL Log-In with PHP - How often? - php

Okay this might be an obvious question, but as soon as i call MySQL with PHP (whhich means i log in) and then close the PHP tag, (shown below) Do I have to call the database again later?
$mysqli = new mysqli("host", "username", "pw", "dbname");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$res = $mysqli->query("SELECT EmbedURL FROM Videos ORDER BY RAND() LIMIT 8");
etc...
And then I need to call it again later in the script to fetch something else fromt he database. Do i have to log into the database again?
Thank you!

The database connection will stay open if you do not close it manually. The only possible cause I can imagine that you could loose the connection is the connection timed out or was closed by the databse because you have to many active connections.
It looks like the database variable is nested deeply in your code. You will also loose the reference of the connection if you close the current code block (}).
Here is a post about MySQL connection pooling which could be insteresting for your problem: Connection pooling in PHP

Related

PHP Warning: mysqli_connect(): (HY000/1040): Too many connections [duplicate]

For now, I have one connect.php file e.g.
$mysql_host = "";
$mysql_database = "";
$mysql_user = "";
$mysql_password = "";
$con = new mysqli(
$mysql_host,
$mysql_user,
$mysql_password,
$mysql_database
);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
In every other PHP file that uses MySQL queries, I use "include 'connect.php';"
For Instance on W3Schools, they create for every query a new connection and then close it after use. See here: w3schools.com: I'm not sure if they do it just for showing purpose, or if it is best practice to do it this way.
Do I have to close the connection after each selection and then establish a new one, for the next query? If not, when do I finally have to close the connection? On the end of the PHP File with all the queries?
A quote from the php.net site.
Open non-persistent MySQL connections and result sets are automatically closed when their objects are destroyed. Explicitly closing open connections and freeing result sets is optional. However, it's a good idea to close the connection as soon as the script finishes performing all of its database operations, if it still has a lot of processing to do after getting the results.
Source: http://php.net/manual/en/mysqli.close.php
Close the connection when you are done using it for that page. If you have, say, a blog, the button that you use to post it would start the code that would open the connection, do some work with the connection (like adding it to your db and or showing it on a page) and then it would close the connection so that it isn't open any longer than it needs. But when you click the button again it would start the process over, only using resources as it needs them.
Best practice is to use close function in footer.php

connecting to multiple databases on different servers in php

I am trying to connect to two different databses using php
error_reporting(E_ALL);
$con= mysqli_connect("localhost", "phpapp", "phpapp", "hazard") or die("error connecting database 1".mysqli_error($con));
$con_vpn= mysqli_connect("xxx.xxx.xxx.xxx", "user", "pass", "db_name") or die("error connecting database 2".mysqli_error($con_vpn));
When I run the application it is showing error : error connecting database 2. It is not even printing the error.
thanks in advance:)
That's because you're trying to use a handle from a failed connection. Since the connection failed, that handle is invalid. That's why there mysqli_connect_error(), which will return the error message from the LAST attempted connection.
$con_vpn = mysqli_connect(....) or die(mysqli_connect_error());
Note that the connect_error function takes no parameters - it doesn't need any.

Website - Connecting to MySQL database

I am aware this is a stupid question, but to connect to a database that is on my local server, do i connect via this code:
mysql_connect("localhost","user","pass")
so using localhost connection. This seems to make sense, as it is sending a message to the host computer to connect to it's local database.
or do i use this piece of code:
mysql_connect("Ipaddress","user","pass")
This also makes sense to me somehow. Which one do i use for my website which i am hosting at home.
EDIT: obviously I want it so that people from all over the world enter information, and it is sent to a database. It isn't meant to be used by me.
A better way to do this is:
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
};
?>
This is what I personally use, there are other ways to do this.
You should use localhost:
You could something like this:
<?php
$mysql = mysql_connect("localhost", "user", "pass");
if(!mysql){
die('Could not connect: ' . mysql_error());
}
//code her
mysql_close(mysql) //stops the connection
?>
Your database will most likely be stored on the same server as your program, you should put localhost.
Anyway, take some time to learn about PDO. It's more secure, cleaner and actually easier to use.

mysql_close(): 5 is not a valid MySQL-Link resource in C:\wamp\www\Includes\footer.php on line 4

Everyth worked fine, it just decided to stop working and it ruined my whole project and Im at standstill.
This is error:
mysql_close(): 5 is not a valid MySQL-Link resource in
C:\wamp\www\Includes\footer.php on line 4
This is footer.php
<?php
//close connection
if (isset($dbh)); {
mysql_close($dbh);
}
?>
This is connect.php
//set constants
require("quick.php");
//database connection
$dbh = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if (!$dbh) { //check connection
die("Cannot conect! to database ");
}
//selecting database
$db_select = mysql_select_db(DB_NAME, $dbh);
if (!$db_select) { //check connection
die("Cannot connect to database ");
}
?>
Basically whenever I try to quit mysql this error shows.
And it all worked fine not long ago.
Try this instead:
if (isset($dbh) && is_resource($dbh)) {
mysql_close($dbh);
} else {
mysql_close();
}
From manual:
mysql_close() closes the non-persistent connection to the MySQL server
that's associated with the specified link identifier. If
link_identifier isn't specified, the last opened link is used.
Maybe he's having few connections.. Who knows..
Somewhere, within your page, there is an assignment that puts $dbh = 5; that overrides your database connection. That is the cause for the error. Search for any assignments to that variable between your database opening and your footer, and you've found your problem.
Note: I wouldn't be that worried about the connection being open as some other commenters here, since if it's not a persistant connection, it will anyway be closed at the end of the script, so I don't see how that would be ruining your whole project. Your code tries to close it at the footer which is not much different than letting it close itself. From the manual:
Using mysql_close() isn't usually necessary, as non-persistent open
links are automatically closed at the end of the script's execution.
See also freeing resources.
All the mysql_* functions will assume "the last connection you opened" if you don't specify a connection. This is useful because you don't have to keep track of it like you do for other libraries. Most likely here you are overwriting the variable $dbh somewhere. Personally I'd use a variable like $_connection if I use one at all.
So just mysql_close() will be enough to close the connection. You need only worry about this kind of thing if you are handling more than one connection at a time.

Correct Procedure for mysqlConnect

I am new to php syntax and am looking for advice on creating the most acceptable or correct code. I focus on front end design, but I like to make sure my code is proper. I am in a digital media program, my instructor has given us this code for connecting to our MYSQL databases.
<?php
mysql_connect("localhost", "root", "root")or die("Cannot Connect to DB");
mysql_select_db("Example")or die("cannot select the DB Example ");
?>
However when I look at connect scripts online they set the mysql_connect function as a variable lets say $connect and run an if statement stating; if not $connect produce error, and the same for mysql_select_db. They also close the script with mysql_close($connect); like below
<?php
$connect = mysql_connect("localhost", "root", "root");
if (!$connect)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("Example", $connect);
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysql_error());
}
mysql_close($connect);
?>
Is either one better? What problems can I have if I dont close the connect with mysql_close?
Regarding using an if instead of an or, it doesn't matter. The or short-circuits, so if the connection worked, die(...) won't be executed. Using either is a matter of preference. If you want to use the or version while keeping the result of the mysql_connect() call, simply assign the whole expression to a variable:
$connection = mysql_connect(...) or die('Connection failed.');
mysql_close() should be used after you're done with all your database communication.
The other mysql_*() functions will use the connection created by the latest call to mysql_connect() or mysql_pconnect(). If for some reason you want more than one connection, trusting the implicit connection object in this manner will fail. Better is to store the connection object yourself and passing it in wherever you need it.
Also before starting to work with databases, you should be aware that mysql is not secure anymore and is deprecated, you should use mysqli. You can use it also as object oriented language.
more details : http://www.php.net/manual/en/book.mysqli.php
example :
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Categories