PHP - Mysqli Extension And Persistent Connections
How do I code a persistent connection with mysqli and PHP?
I know back in mysql it was mysqli_pconnect, what is it for mysqli? Please do not refer to this page (http://www.php.net/manual/en/mysqli.persistconns.php) as it gives no example and makes little sense. Many thanks in advance. Similar TutorialsHi, I'm building a flash environment for a small scale MMO game, and I need to employ the use of sockets so that users can interact with each other in real time (chat, battle, exploring, etc). I've done quite a bit of Googling, and haven't turned up much useful information. Maybe I'm looking for the wrong thing? Anyway, I have my own server, running Fedora 9 and Apache 2.0. I want to create a PHP "socket server" that runs almost as a process on my server, so that users can connect to it and pass data between each other instantly. I've looked through PHP's manual on the socket functions, and I'm fairly confident that I will be able to work with them just fine as soon as I actually have the socket server working.. So my question is, how exactly would I go about starting this process? I'm messing around on the command line right now and can't seem to get it to work? Thanks, nethnet I am adding a "Welcome Message" in my Header file - which is included in every page on my website. If the user is logged in, they would see something like, "Welcome, Debbie!! What is the best approach to take with storing (and checking) the "LoggedIn Status" and "User's Name"? Do I just store them both in a SESSION and access them? Or should I be checking for these two values from my back-end database? It seems to me that a couple of weeks ago I got into some big debate with people about "persistence" and whether it was okay of not to store information in the SESSION... What do you think? Thanks, Debbie I was wondering what the users at phpfreaks recommend as far as persistent database connections. Is it better to save the connection, or to open up a new connection for each page? Also, how would you have a persistent connection? Wasn't really sure what to call this topic, and I'm also not sure how to ask this question. Here is what I have, and the problem I'm having. I have an html form on a webpage that sends information into 2 different tables in a database I have. One table is not important to the topic, the other table is where i'm having my problem. The user submits their information from the form and the info goes into the tables. There is another page that displays the names of the users on a "wall" that populates from the second table in the database. The second table takes information from the form they filled out and displays their name on the wall based on that (most importantly whether or not they can be e-mailed from the wall or not). The issue I am having (and this is probably the long way of asking this) is that when some people fill out the form their info does not go into either database. I know the functionality works, because their have been a couple of users that have signed up and everything worked fine for them. I'm thinking this may be a connection issue possibly due to a firewall or something. Any ideas on this? The website is http://itgetsbetter.tsagl.org the form to fill out is under the button "Take the Pledge" and the names are displayed under "View the Wall". If someone wouldn't mind to try out the functionality of the form for me (I need people that have some technical experience to do this because most of the people that I work with have no idea what I am talking about when trying to troubleshoot this with them). I assure you that if everything works, I will remove your information from my database. This site is only out to a few people at the moment, but I am planning on taking it public in the next couple of days. I would display code here, but I'm not sure what code you would need to see in order to help with this. I just think this is a connection issue; I just need to know how to test it or how to rectify the issue. Thanks for your help (and please don't hate too much on the design on the site; i'm more of a programmer than a designer). Hi, I would just like to know what limitations apply for opening X amount of connections to different websites with Curl? (specifically, I'm using Curl multi and have my own way of regulating how many connections occur at a given time). I ask this because it seems I can open 100 connections and get the info from the websites quite quickly. If I were to open say 1000 would that crash my router or what would happen? Thanks in advance! On my new site on average every page that loads opens 9 MySql connections and runs 14 MySql Queries, And as I use Ajax to dynamically update the pages, so this repeats every 60 seconds per page. Is this too many connections? I am not having any problems at the moment but the site is getting more busy, and I don't want the site to start running slow, or the MySql server to crash. Any comment would be much appreciated. At the moment I am writing an application that supports plugins. Every plugin implements an interface so that the main application can control the plugin with the interface methods. There could be plugins that need a database connection and others that do not. What I am doing at the moment is loading every plugin with a __construct($databaseHandler). For plugins that don't need a database connection this is a little overhead. I could also use a Singleton or something else "staticish" so that the plugin can get the database instance whenever it wants, but then the plugin can only be used for my application where this specific Singleton is present and maybe I would like to use the plugin for other purposes later in another environment without changing it. Do you have any better ideas or how do you normally manage your database connections? I've looked every where, probably googled every variation of my question I could come up with and I've tried all of the suggestions... I'm trying to connect to two different DBs in two different locations ($local and $remote) and only the second one works. Here is a sample of my code ("..." = hidden): //-------------Local DB Connection: $local = mysql_connect("localhost","root","..."); if (!$local) { die('Could not connect: ' . mysql_error()); } $sel1 = mysql_select_db("new", $local); //-------------Remote DB Connection: $remote = mysql_connect("...","...","...",true); if (!$remote) { die('Could not connect: ' . mysql_error()); } $table = "..."; //---------function selecting from local: function fncGrabNemsis($ele,$val){ mysql_select_db("new", $local); $result = mysql_query("SELECT * FROM new.tblvalues WHERE fldelement='$ele' AND fldcode='$val'",$local); $tmprow = mysql_fetch_array($result); return (isset($tmprow['fldvariable'])?$tmprow['fldvariable']:$val); } //----------Select run from Remote: mysql_select_db("ImdxTest", $remote); $result = mysql_query("SELECT * FROM ImdxTest.$table WHERE ClientID = ... AND IncidentNum = '$fldINCID'", $remote) or die(mysql_error()); $row = mysql_fetch_array($result); I've tried moving the mysql_select_db() function calls everywhere you can think of and just about everything else... What happens is, I get php errors saying that $local is not defined or that the mysql function that are trying to use the $local connection are expecting parameters to be resources!? I know for a fact that both connections work because individually they both work. Only the second connection ($remote) works... Thanks a lot for any suggestions! Hi, Just a quick query. I call my db connection and configuration files on every script. I also have just made a functions script where i'm storing some functions except when i call the function, my script fails because of a missing database connection. But on the page that fails, i call the configuration files including the db connection at the start of the script. But when i get to where i include the function they are all on the same script so should it fail?? The page did work fine when the function was inbedded in the script. But as i'm using the function on a few pages, i thought it would be better practise and more efficent to just include the function on each page i need, rather than just copy and paste all the php in the required pages. Or do i have to declare the db connection inside the function page as well??? Thanks Hello guys, I hope you can help. I can't get my page to switch between two database connections properly It seems to ignore the second connection. I'm trying to go through each group in database one and find out how many members they have registered in database two by checking the field "tsName". This is a valid query for database one. $fetchUsers = mysql_query("SELECT * FROM $db_corps_table ORDER BY cName;", $con1); This is a valid query for database two. $fetchUsers = mysql_query("SELECT * FROM 'users' WHERE tsName LIKE $cTicker%;", $con2); However despite me specifying which database link to use it tries to use every query on database one ($con1). So I can never query database two ($con2) because it just breaks with the result below. :S $fetchUsers = mysql_query("SELECT * FROM $db_corps_table ORDER BY cName;", $con1); gives Quote AREA 43 [A-43] (11): result result result (there are 3 groups in database one) But: $fetchUsers = mysql_query("SELECT * FROM 'users' WHERE tsName LIKE $cTicker%;", $con2); gives Quote AREA 43 [A-43] (11): Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/sever/public_html/mav/tools/ts_corp_registrations.php on line 51 <?php // ===== Connect to database one (group) ===== $con1 = mysql_connect($db_host,$db_corps_user,$db_corps_pass); if (!$con1) { die("Could not connect:" . mysql_error()); } $db_select1 = mysql_select_db($db_corps_db, $con1); if (!$db_select1) { die ("Could not select database:" . mysql_error()); } // ===== Connect to database two (members) ===== $con2 = mysql_connect($db_host,$db_ts_user,$db_ts_pass, true); if (!$con2) { die("Could not connect:" . mysql_error()); } $db_select2 = mysql_select_db($db_ts_db, $con2); if (!$db_select2) { die ("Could not select database:" . mysql_error()); } $fetchCorps = mysql_query("SELECT * FROM $db_corps_table ORDER BY cName;", $con1); while ($row = mysql_fetch_array($fetchCorps)) { // For each of the results, gather details from database one, then see how many members we can find in database two $cName = $row["cName"]; $cTicker = mysql_real_escape_string($row["cTicker"],$con1); $cMembers = $row["cMembers"]; echo $cName." [".$cTicker."] (".$cMembers."):<br />"; // ========================== HERE BE PROBLEMS ========================== //$fetchUsers = mysql_query("SELECT * FROM $db_corps_table ORDER BY cName;", $con1); $fetchUsers = mysql_query("SELECT * FROM 'users' WHERE tsName LIKE $cTicker%;", $con2); // =================================================================== while ($rowTS = mysql_fetch_array($fetchUsers)) { echo "result<br />"; } } // all done, close DB connections mysql_close($con2); mysql_close($con1); ?> Hey, I would there be a way i could create a form in which upon entering a domain name/URL it will tell you how many connections there are to the site and how many (if any) MySQL queries are running? If I add this line to a wordpress footer it displays the number of sql queries. Code: [Select] <?php echo get_num_queries(); ?> queries in <?php timer_stop(1); ?> seconds. Any help is greatly appreciated. Thanks. Hi Have an issue with a script that connects to multiple Access databases to extract data. There is one master database and then numerous small databases (I take no responsibility for the design!). The master is opened and then the sub databases are looped around, opened process and closed in turn. However after about 20 connections I get the error [ODBC Microsoft Access Driver] Too many client tasks for any new connections. It is related to the number of connections rather than the number of operations on databases (ie, if I comment out one of the pieces of SQL run on each database it makes no difference). I am closing the connection and unsetting the variable that stores the connection. As such there shouldn't be an excess of connections open at any one time. Any suggestions? All the best Keith Hello, I'm trying to update my database with current statistics from my gameservers, but running the loop of socket connections to all of the servers on page load takes too long. For every server in the array it takes roughly 4 seconds to complete each one.. with a massive list of say 42 it takes awhile. However, I'm running from shared hosting and was wondering if that was the reason each server takes so long to query. I was thinking about running a cron job every 1 minute to update the information so it's still relativity new and current. Will the 1 minute cron job affect anything from the shared hosting? I'm using 1and1 web-hosting on a 1&1 Business Package. Thanks Hi everybody, I am facing "Too many connections" problem on my site. in fact the server is moved from one location to,another and after the movement this problem arise... Pls help. Thanks Hi, I am quite new to using php classes so it maybe something simple here, however I am trying to establish to connection to two different databases using one PHP class; The problem is that this will work for one but when I create a new connection they will both fail.
<?php putenv("TZ=Europe/London"); // start database connection $funky_db = new Database('xxxx', 'xxxx', 'xxxx', 'xxxx'); // start database connection $funky_cc = new Database('xxxx', 'xxxx', 'xxxx', 'xxxx'); class Database { private $host; private $user; private $pass; private $name; private $link; private $error; private $errno; private $query; function __construct($host, $user, $pass, $name = "", $conn = 1) { $this -> host = $host; $this -> user = $user; $this -> pass = $pass; if (!empty($name)) $this -> name = $name; if ($conn == 1) $this -> connect(); } function __destruct() { @mysql_close($this->link); } public function connect() { if ($this -> link = mysql_connect($this -> host, $this -> user, $this -> pass, TRUE)) { if (!empty($this -> name)) { if (!mysql_select_db($this -> name)) $this -> exception("Could not connect to the database!"); } } else { $this -> exception("Could not create database connection!"); } } public function close() { @mysql_close($this->link); } public function query($sql) { if ($this->query = @mysql_query($sql)) { return $this->query; } else { $this->exception("Could not query database!".$this->name); return false; } } public function num_rows($qid) { if (empty($qid)) { $this->exception("Could not get number of rows because no query id was supplied!"); return false; } else { return mysql_num_rows($qid); } } public function fetch_array($qid) { if (empty($qid)) { $this->exception("Could not fetch array because no query id was supplied!"); return false; } else { $data = mysql_fetch_array($qid); } return $data; } public function fetch_array_assoc($qid) { if (empty($qid)) { $this->exception("Could not fetch array assoc because no query id was supplied!"); return false; } else { $data = mysql_fetch_array($qid, MYSQL_ASSOC); } return $data; } public function fetch_object($qid) { if (empty($qid)) { $this->exception("Could not fetch object assoc because no query id was supplied!"); return false; } else { $data = mysql_fetch_object($qid); } return $data; } public function fetch_all_array($sql, $assoc = true) { $data = array(); if ($qid = $this->query($sql)) { if ($assoc) { while ($row = $this->fetch_array_assoc($qid)) { $data[] = $row; } } else { while ($row = $this->fetch_array($qid)) { $data[] = $row; } } } else { return false; } return $data; } public function last_id() { if ($id = mysql_insert_id()) { return $id; } else { return false; } } private function exception($message) { if ($this->link) { $this->error = mysql_error($this->link); $this->errno = mysql_errno($this->link); } else { $this->error = mysql_error(); $this->errno = mysql_errno(); } if (PHP_SAPI !== 'cli') { ?> <div class="alert-bad"> <div> Database Error </div> <div> Message: <?php echo $message; ?> </div> <?php if (strlen($this->error) > 0): ?> <div> <?php echo $this->error; ?> </div> <?php endif; ?> <div> Script: <?php echo @$_SERVER['REQUEST_URI']; ?> </div> <?php if (strlen(@$_SERVER['HTTP_REFERER']) > 0): ?> <div> <?php echo @$_SERVER['HTTP_REFERER']; ?> </div> <?php endif; ?> </div> <?php } else { echo "MYSQL ERROR: " . ((isset($this->error) && !empty($this->error)) ? $this->error:'') . "\n"; }; } } ?> I was curious.. I read that after using a PDO connection you should set the object to null to close it out. In this instance: Code: [Select] function IsOwner($regionid, $user) { global $Username, $SQL_Server, $SQL_User, $SQL_Pass; $pdo = new PDO("mysql:host=$SQL_Server;dbname=$SQL_Database", $SQL_User, $SQL_Pass); $sql = $pdo->prepare("SELECT count(region_id) FROM region_players WHERE region_id = ? AND user_id = ? AND owner = 1"); $sql->execute(array($regionid, $user)); if ($sql->rowCount() == 0) { return false; } else { return true; } $pdo = null; } Since the return is called prior to the nulling, does it leave a connection hanging or does PHP do some sort of auto-closeout when a function ends? Should I instead be doing: Code: [Select] function IsOwner($regionid, $user) { global $Username, $SQL_Server, $SQL_User, $SQL_Pass; $ownerstatus = false; $pdo = new PDO("mysql:host=$SQL_Server;dbname=$SQL_Database", $SQL_User, $SQL_Pass); $sql = $pdo->prepare("SELECT count(region_id) FROM region_players WHERE region_id = ? AND user_id = ? AND owner = 1"); $sql->execute(array($regionid, $user)); if ($sql->rowCount() > 0) $ownerstatus = true; $pdo = null; return $ownerstatus; } ? OK, so I dont think this is a code issue as such, but I am completely stumped as to where the issue could be. I have a page with some standard include() functions at the top. When I access the page from home, everything operates as it should, when I access it from work (on multiple machines), I get the standard "unable to open stream" and "unable to access" warnings for the include statements. I have tried hard refreshing and deleting cache (not that it should make a shred of difference) etc, but the error is still there after a week or so. Does anyone know what could be causing this issue? after inserting data i get 0 sometimes i created a mysql_connect for it Code: [Select] <?php $maincon = mysql_connect('local', "root", "root"); mysql_select_db("root"); then //insert and $success = mysql_query($query); echo $ref_id = mysql_insert_id($maincon); ?> $ref_id is returned as 0, although the connection is there var_dumping the query returns the values |