I have this php code, the files are hosted on another server and db else where
$hostname_xxx = "xxxdb.db.234141.mysqldbhosted.com";
$database_xxx = "xx11xx";
$username_xxx = "xx11xx";
$password_xxx = "xx332211xx";
$shasown = mysql_pconnect($hostname_xxx, $username_xxx, $password_xxx) or trigger_error(mysql_error(),E_USER_ERROR);
$your_ip = $_SERVER['REMOTE_ADDR'];
echo $your_ip;
$insertSQL1 = "INSERT INTO table (users_ip) VALUES ('$your_ip)";
mysql_select_db($database_xxx, $xxx);
$Result21 = mysql_query($insertSQL1, $xxx) or die(mysql_error());
The error I am getting is
Warning: mysql_pconnect() [function.mysql-pconnect]: Lost connection to MySQL server during query in /domains/4444.com/html/55.php on line 8
Fatal error: Lost connection to MySQL server during query in /domains/4444.com/html/55.php on line 8
Thanks
Jean
mysql_pconnect() creates a persistent connection to the database, whereas mysql_connect() does not. IF you are creating a persistent connection, you need only connect once throughout your session, so if you're creating a persistent connection more than once this may be the cause.
On shared servers it may be worth trying mysql_connect() over mysql_pconnect() and see if this corrects the issue at hand. Also, in your code you have:
$Result21 = mysql_query($insertSQL1, $xxx) or die(mysql_error());
But should be:
$Result21 = mysql_query($insertSQL1, $shasown) or die(mysql_error());
because $xxx was never a connection variable but $shasown is.
Personally I like to use mysqli_connect() as I find it to be a little faster.
Related
This question already has an answer here:
What is the best way to minimize number of connections?
(1 answer)
Closed 2 years ago.
When a user logs in the site, an AJAX call is made every 10 seconds, to update data from a delivery service.
It works OK, but at night when the demand for deliveries increases a lot, there begin to be these connection errors.
I'm on a GoDaddy server, so I can't change the 'max_user_connections' to a higher value.
I was reading about persistent connections, but I don't know if it will work.
By adding a "p:" to the connection before the host like this:
$link = mysqli_connect("p:" . DB_HOST, DB_USER, DB_PASS);
I think that when an AJAX call runs a new connection to the DB is made in the PHP file.
Will the persistent connection avoid this and reuses a connection that each users already has?
If a persistent connection is not the right path for this, what could it be?
Errors in PHP Log:
[06-Dec-2020 00:13:22 UTC] PHP Warning: mysqli_connect(): (42000/1226): User 'delivery' has exceeded
the 'max_user_connections' resource (current value: 30) in
/home/ofc1m1i4xaac/public_html/xdelb.com/classes/get_delivering.php on line 15
PHP file get_delivering.php:
<?php
session_start();
session_write_close();
if (!isset($_SESSION['user_id']) ) {
// header("Location: ../index.php");
exit();
}
require_once("../includes/psl-config.php");
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS);
mysqli_select_db($link, DB_NAME);
mysqli_set_charset($link, "utf8");
$append="";
$number=1;
$result = mysqli_query($link, "SELECT orders_header.`id`, `picking_time`, `delivery_address`, orders_header.`created_at` FROM `orders_header` inner join delivery_guys on delivery_guys.id=dv_guy_id `store_id`=".$_SESSION['user_id'] );
if ( mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)){
// do stuffs
}
}
mysqli_close($link);
I don't think that persistent connections will help you,
basically your issue of max_connection_error will remain the same or even worst.
So I will suggest take #dave advice and to deploy your website to another host that you can change this configuration or to your own VPS server that ypu can control it and change what ever you want.
This is to docs from PHP website where you can fond more info about persistent connections, advantages and disadvantages
https://www.php.net/manual/en/features.persistent-connections.php
More info and tests results you can find in this website:
https://meta.wikimedia.org/wiki/Why_persistent_connections_are_bad
I usually am immersed in the Microsoft Stack but dabble in PHP from time to time. A long standing question I've had with PHP that I've never seem to be able to find the answer to is how do you apply your already declared require("dbConnect.php") database connection to your mysql_query()? For clarification please see my code example below:
require("dbConnect.php");
$db_host = 'localhost';
$db_user = 'UserName';
$db_pwd = 'Password';
$database = 'DbName';
$table = 'tblQuote';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT QuoteID, FirstName, LastName, PhoneNumber, Email, QuoteDate FROM tblQuote ORDER BY QuoteDate DESC");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
So in looking at this you can see the standard require() declaration at the top... which already holds my connection info. But every single MySQL Query example I've ever found always creates it's own connection... which I get for demonstration purposes... but I've never been able to figure out how I can use my already existing connection thereby bypassing rewriting the exact same connection info over and over again when it comes to writing queries. I know for you PHP developers this question is like 101 but I've not been able to find an answer to this seemingly basic question... admittedly I may be asking the question wrong so any help would be appreciated!
From the PHP documentation: http://php.net/manual/en/function.mysql-query.php
mixed mysql_query ( string $query [, resource $link_identifier = NULL ] )
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments.
So since you've already created one in your dbConnect.php, the one you just made will be used (It won't create a new one for every query). To pass it explicitly into your mysql_query function call, you can return the MySQL resource that was returned from your mysql_connect call like so:
dbConnect.php
return mysql_connect(....);
Then in the code you pasted above:
$mysql_conn = require('dbConnect.php');
...
$result = mysql_query('...', $mysql_conn);
Then you will explicitly have the connection and pass it to your query - there will be no mistaking it, regardless of how large your codebase becomes. When you require the file, you'll have access to the connection variable, but in the above example, how you get the connection is more semantically clear.
Also, notice that this function has been deprecated in PHP>=5.5, so you'll want to use PDOs or MySQLi which have future support.
Hope this helps!
I'm trying to get work this small project. I have master-admin over classic admin.
my database connection is establish on cookie $key. If i have cookie google, it looks into my master-admin database and search there for DB_PASSWORD, DB_HOST etc. And then it build config.php.
This cookie is set to expire after few days.
This is my config.php :
<?php
$key = $_COOKIE["nazev_webu"];
$sql = mysql_query("SELECT * FROM weby WHERE nazev='$key'");
while($row = mysql_fetch_array( $sql )) {
// Print out the contents of each row into a table
$name = $row['DB_NAME'];
$pass = $row['DB_PASSWORD'];
$user = $row['DB_USER'];
$host = $row['DB_HOST'];
}
//připojení dataze
$connect = mysql_connect($host, $user, $pass)
or die("Nelze se připojit k databázi");
//výběr databáze
$select = mysql_select_db($name ,$connect)
or die("Nemohu vybrat databázi");
?>
it works perfectly but only in "read only mode". I can select from database but if I'm trying to insert or update something i get this error.
Warning: mysql_query() [function.mysql-query]: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) in /data20/website/html/config.php on line 7
Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /data20/website/html/config.php on line 7
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /data20/website/html/config.php on line 9
Warning: mysql_connect() [function.mysql-connect]: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) in /data20/website/html/config.php on line 20
I have to say that insert and update action are build on ajax call, so i post via ajax id of article f.e.. to the update script.
I think problem can be that mysql are on another server, not on the same server as is my website.
The solution is too easy. I forgot to include static database connection into this file. So it can't look into database and get from here connection details for new config.php.
I am attempting to create a separate login file for database connections as I am not too fond of having all the access details on each page that requires database access.
I have created a separate file on my server that contains the variables required for a successful login and then use the;
include_once('path_to_file/filename.php');
to get the variables and then use;
$dbconnection = mysqli_connect("$hostname","$username","$password","$database") or die ("Could not connect to the server");
but the connection fails every time. I tried including the connection script in the file I am attempting to include but then I get this message:
Can't connect to local MySQL server through socket '/tmp/mysqld.sock' (2)
I'm not really sure how to fix this, but every page in my server more or less access the database and I think it has to be a security risk having login details replicated everywhere!
Anyone have any suggestions or alternatives?
databaseloging format is:
<?php
# parameters for connection to MySQL database
$hostname="hostname";
$database="databasename";
$username="username";
$password="password";
?>
P.S. I have also tried require and got the same result.
Also when using multiple MySQL connections in PHP, you have to supply a fourth argument telling PHP to actually create new connections like this (this is very important, if you are using two connections to the same host):
$db1 = mysql_connect($host1, $user1, $passwd1, true);
$db2 = mysql_connect($host2, $user2, $passwd2, true);
If the fourth argument is not used, and the parameters are the same, then PHP will return the same link and no new connection will be made.
After this you should use "mysql_query" with an extra parameter than defines which connection to use:
$res1 = mysql_query($sql1, $db1) or die(mysql_error($res1));
$res2 = mysql_query($sql2, $db2) or die(mysql_error($res2));
http://www.php.net/manual/en/function.mysql-connect.php
I am getting this error:
Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource
Here's my Connection.php :
$userDB_server = "";
$userDB_user = "";
$userDB_password = "";
$userDB_database = "";
$connection = mysql_connect("$userDB_server","$userDB_user","$userDB_password") or die ("Unable to establish a DB connection");
$userDB = mysql_select_db("$userDB_database", $connection) or die ("Unable to establish a DB connection");
$gameDB_server = "";
$gameDB_user = "";
$gameDB_password = "";
$gameDB_database = "";
$gameDB_connection = mysql_connect("$gameDB_server","$gameDB_user","$gameDB_password", true) or die ("Unable to establish a DB connection");
$gameDB = mysql_select_db("$gameDB_database", $gameDB_connection) or die ("Unable to establish a DB connection");
Here's my function :
require_once('Connection.php');
$findQuery = sprintf("SELECT * FROM `Keys` WHERE `ID` = '$gID'");
$findResult = mysql_query($findQuery, $connection) or die(mysql_error());
$resultRow = mysql_fetch_assoc($findResult) or die(mysql_error());
The error is on "$findResult = mysql_query($findQuery, $connection) or die(mysql_error());"
But I don't see a problem anywhere.
What I've tried :
I've tried with and without the "true" on the second connection,
didn't seem to make a difference anywhere.
Echoing the $connection and $gameDB_connection shows nothing,
Using var_dump on $connection shows "resource(9) of type (mysql link)"
Removing the $connection from the mysql_query has it connect to the
other DB (gameDB_connection) and I get an error that the table
doesn't exist (its not on that DB).
Adding / changing / removing the backquote ( ` ) from the query seems
to have no effect on the error
The variable $gID echo's correctly, so it's not null (its 1001 in
this case)
If I run the SELECT part in the actual sql form (instead of via php),
it lists them all correctly
The Connection.php is used in other places (one page reads
from both databases at the same time) successfully. No errors anywhere else
Anyone have any idea what's wrong?
Based on the comments, it sounds like the problem is caused by using require_once() inside a function.
One of two thing is happening. Either:
You've already included Connection.php somewhere else, so when you get to the function, it's not actually included.. because of the once part of require_once.
or...
It is working the first time you call the function, but the second time you call it, the file has already been included and does not get included again.
The problem is that when the file is first included (assuming that's from within this function), the $connection variable is created in the function scope, and like any other function variable, is gone at the end of the function. When you call the function a second time, the include doesn't happen because you're using require_once.
You could probably fix this by calling require() instead of require_once(), but that will end up reconnecting to the database every time you call the function - which is a lot of unnecessary overhead. It's much cleaner to just move the include outside of the function, and either pass the connection into the function, or use it as a global variable.
That would look like this:
require_once('Connection.php');
function getResult() {
global $connection;
$findQuery = "SELECT * FROM `Keys` WHERE `ID` = '$gID'";
$findResult = mysql_query($findQuery, $connection) or die(mysql_error());
$resultRow = mysql_fetch_assoc($findResult) or die(mysql_error());
}
All that being said, there's 2 major problems with this code.
You're using the mysql_* functions which are deprecated and will soon be removed from new versions of PHP. See this question for more details: Why shouldn't I use mysql_* functions in PHP?
It's not actually that hard to switch to something like the mysqli_* functions instead - there's a non-object set of functions that are almost identical to what you're using now.
You're including a variable in your query without properly escaping it. At the very least you should be calling mysql_real_escape_string() (or mysqli_real_escape_string()), but a better solution is to look into prepared statements. You can find more information on prepared statements here: How can I prevent SQL injection in PHP?