PHP - Mysql Connection - Why Shouldn't You Do This?
The below scenario works fine but why shouldnt you do this?
Why can I not just run the mysql_connect and mysql_select_db at the top of each page and then run my queries under all of this. What I have read is that the mysql_connection will die after the script finishes (at the end of the page) any way so why do people create mysql_connection objects as php is stateless so it doesnt save this any way. Code: [Select] <?php mysql_connect('localhost', 'user', 'pass'); mysql_select_db('test'); ?> <html> <body> <?php $query = mysql_query("Select * from data"); while($row = mysql_fetch_array($query)) { echo $row['name']."<br />"; } ?> -------------- OTHER HTML HERE --------------- <?php $query = mysql_query("Select * from addresses"); while($row = mysql_fetch_array($query)) { echo $row['postcode']."<br />"; } ?> </body> </html> Similar TutorialsSay a script has ignore_user_abort(true); set. If the user aborts the connection and print is called, the buffer doesn't get written anywhere. So shouldn't print() return false in this case? To clarify, I know it doesn't, but shouldn't it? If not, why not? hi everyone I have a question... does creating a connection to mysql takes time depeding on the database size? Lets say that in my entire project I will be connection to 4 databases so I created a config.php which looks like this: Code: [Select] $hostname = "localhost"; $username = "root"; $pword = ""; $con1 = @mysql_connect($hostname,$username,$pword,true); @mysql_selectdb("databasename1",$con1); $con2 = @mysql_connect($hostname,$username,$pword,true); @mysql_selectdb("databasename2",$con2); $con3 = @mysql_connect($hostname,$username,$pword,true); @mysql_selectdb("databasename3",$con3); $con4 = @mysql_connect($hostname,$username,$pword,true); @mysql_selectdb("databasename4",$con4); so, this file is included in every pages, I put this on the top. Basically every page request it will open 4 connection and the script will only use 2 connection and another page will only 1 and so on..... this style is very convenient as for I am not creating a connection in every page.. But my concern is will it effect the performance of my system? Tnx in advance..... Perhaps this is a rather lay question, but, is there a way to gather specific connection details about an open MySQL connection in php? Example: <?php $connect = mysql_connect('localhost', 'username', 'password'); ?> Using the $connect variable, could I run a command that dumps the host, and username to a log file?? Thanks in advance, I'm still searching. E I have a class and a lot of the function in the class require a connection to a MySQL database. At the moment I am using the "__construct()" to connect to the database each time a new instance of the classes is created. Is this the best way to do it or should I have a separate class for connection to the database? Just wanted to get an idea of what other people do. Thanks for any help. Hi Friends, i am new one to this.i have a big problem i think i will get the correct solution... when i am connecting to the MySql Database i am getting this. Warning: mysql_connect() [function.mysql-connect]: Lost connection to MySQL server at 'reading initial communication packet', system error: 110 in /home/txtimg0/public_html/cherple/Scheduled_Campaigns.php on line 24 unable to select database define("prod_dbuser","xxxx"); //gtmdev1 define("prod_dbpass","xxxxx"); //gtmdev1 define("prod_database_cm2","cm2"); define("prod_database_glue","glue"); define("prod_hostname","xxxxxxxx"); i am defined these constants in gtm _constants.php i am includeing this file when ever i need to connect with database. this working fine in past.now we installed the new Database from then i am getting this error. can any one Please me Help to Resolve this Issue.? and why php is not connecting to the database??? Thanks, Ramky I am slightly puzzled when I attempt to connect to MySQL using variables, if I use this:- Code: [Select] // Connect to MySQL and select dbase mysql_connect("$host", "$user", "$pwd") or die("Computer say NO!"); mysql_select_db("test_site") or die("I've just had a senior moment, and cannot connect to the database..."); I get this error:- Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'root'@'localhost' (using password: YES) in C:\wamp\www\php\test site\regproc.php on line 24 Computer say NO! Whereas if I use this:- Code: [Select] // Connect to MySQL and select dbase mysql_connect("localhost", "root", "my password") or die("Computer say NO!"); mysql_select_db("test_site") or die("I've just had a senior moment, and cannot connect to the database..."); it works perfectly. Most of the tutorials I have read seem to indicate that one can use variables in this case, so I do not understand why it doesn't work... I am trying to get data out off a mysql database, by using an php file. But i am not getting any output?
Examples.html
<html ng-app="countryApp"> <head> <meta charset="utf-8"> <title>Angular.js Example</title> <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script> <script> var countryApp = angular.module('countryApp', []); countryApp.controller('CountryCtrl', function ($scope, $http){ $http.get('category.php').success(function(data) { $scope.countries = data; }); }); </script> </head> <body ng-controller="CountryCtrl"> <table> <tr ng-repeat="country in countries"> <td>{{country}}</td> </tr> </table> </body> </html>category.php <?php $servername = "localhost:3306"; $username = "root"; $password = "root"; $dbname = "myDB"; $conn = mysqli_connect($servername, $username, $password, $dbname); if(!$conn){ die("Connection failed: " .mysqli_connecet_error()); } $showData = "SELECT id FROM myDB"; $data = array(); $result = mysqli_query($conn, $showData); if(mysqli_num_rows($result) > 0){ while($row = mysqli_fetch_assoc($result)){ $data[] = $row; } } else { echo "0 results"; }; print json_encode($data); mysqli_close($conn); echo($outp); ?> Hi,
If I place the following into a file called db.php and save it into folder called includes using xampp:
$dbhost = 'localhost'; Hello guys. Trying to connect php with mysql database and then display results on the screen. This is my code: Code: [Select] <?php $dbhost = "localhost"; $dbuser = "username1"; $dbpass = "password1"; $db = "username1_myDB"; $connection = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Could not connect"); mysql_select_db($connection, $db); $show = "SELECT Name, Description FROM people"; $result = mysql_query($show); while($show = mysql_fetch_array($result)){ $field01 = $show[Name]; $field02 = $show[Description]; echo "id: $field01<br>"; echo "description: $field02<p>"; } ?> However im getting this: Warning: mysql_select_db() expects parameter 1 to be string, resource given in /home/pain33/public_html/index.php on line 20 Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/pain33/public_html/index.php on line 26 Any ideas how to fix this? Thank you. Hey there, total n00b here... Just installed and learned the basic functions of PHP and MySQL (Only have very basic programming background.) Also managed to get an Apache server running. I'm attaching a screenshot that should explain my problem entirely but in short... I can connect to and send SQL queries to my MySQL server using my terminal. My browser reads php statements over the apache server fine and it 'seems' to connect to my MySQL server fine, but it won't select a database and doesn't seem to accept other SQL queries. If I use a non-existant server name I get an error code but when I change to a non-existant user name I don't get an error code. So I'm not sure if it actually does connect or not or why the other queries doesn't work. As I said I'm VERY new to this, so I might be making some other mistake as well. Please see attached document/screenshot. Thank you Ardinent I'm suddenly having trouble using my connection to my MySQL database... (yes it was working but now...) I have the Connection created in an include file and stored in variable $DB, in the main file that includes the file containing the$DB there are other includes for classes. These classes are SUPPOSED to use $DB to connect to and SELECT/UPDATE/INSERT, but for a reason I cant figure out they suddenly stopped seeing $DB. it keeps saying its an undefined variable. If you need to see code I can post... Ok, i really need help with my registration page for my website. I've been working on this for 2 days now and i can't seem to get it to work propertly. This problem is that whenever i'm trying to register myself as a new user at my localhost website i get "Could Not Process Form" error that i've put into the code myself. I beleive this has something to do with the connection to my MySQL but i've put in "membership" as the database "root" as the username and then my password. If anyone has the time to read through my coding, i have marked the line where the error message is placed in the code.. yeah see for your self. Really need help with this! <?php class Register { private $username; private $firstname; private $lastname; private $password; private $passmd5; private $email; private $gender; private $birthday; private $errors; private $token; public function __construct() { $this->errors = array(); $this->username = $this->filter($_POST['username']); $this->firstname = $this->filter($_POST['first_name']); $this->lastname = $this->filter($_POST['last_name']); $this->password = $this->filter($_POST['password']); $this->email = $this->filter($_POST['email']); $this->gender = $this->filter($_POST['gender']); $this->birthday = $this->filter($_POST['birth_day']); $this->token = $_POST['token']; $this->passmd5 = md5($this->password); } public function process() { if($this->valid_token() && $this->valid_data()) $this->register(); return count($this->errors)? 0 : 1; } public function filter($var) { return preg_replace('/[^a-zA-Z0-9@.]/','',$var); } public function register() { mysql_connect("localhost","root","") or die(mysql_error()); mysql_select_db("membership") or die (mysql_error()); mysql_query("INSERT INTO users(username,password) VALUES ('{$this->username}','{$this->passmd5}')"); if(mysql_affected_rows()< 1) $this->errors[] = 'Could Not Process Form'; <------------------ HERE IS THE ERROR MESSAGE I'VE PUT IN THE CODE TO SPIT OUT IF SOMETHING GOES WRONG } public function user_exists() { mysql_connect("localhost","root","") or die(mysql_error()); mysql_select_db("membership") or die (mysql_error()); $data = mysql_query("SELECT username FROM users WHERE username = '{$this->username}'"); return mysql_num_rows($data) > 0 ? 1 : 0; } public function show_errors() { echo "<h3>Errors</h3>"; foreach($this->errors as $key=>$value) echo $value."<br>"; } public function valid_data() { if($this->user_exists()) $this->errors[] = 'Username Already Taken'; if(empty($this->username)) $this->errors[] = 'Invalid Username'; if(empty($this->firstname)) $this->errors[] = 'Invalid First Name'; if(empty($this->lastname)) $this->errors[] = 'Invalid Last Name'; if(empty($this->password)) $this->errors[] = 'Invalid Password'; if(empty($this->email) || !preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]{2,4}$/',$this->email)) $this->errors[] = 'Invalid Email'; if(empty($this->gender)) $this->errors[] = 'Invalid Gender'; if(empty($this->birthday)) $this->errors[] = 'Invalid Birthday'; return count($this->errors)? 0 : 1; } public function valid_token() { if(!isset($_SESSION['token']) || $this->token != $_SESSION['token']) $this->errors[] = 'Invalid Submission'; return count($this->errors)? 0 : 1; } } ?> Hi, im a little stuck trying to work out how to do this. I want to check it there is a mysql connection open on my page and if so, mysql_close($conn);... The reason is that my pages are on a dynamic template, and I would like to chuck this right at the end of the page. is it possible? Thank you, Shaun Hi there, I am having a bit of trouble understanding what I am doing, basically all I want at the moment is to be able to make a very basic introductory guide for myself on my own Database class implementation. I know there are some around on the web but I thought for my own education I would create one of my own, just to see if I can fully understand what it is I am doing. It won't at this present moment involve anything more than a standard class, with 3 properties: protected $_connect This will be the basis for mysql_connect stuff. protected $_query As you probably would have guessed the basis for the mysql_query strings this application will do. protected $_error Then finally any errors that occur will go through this function, right thats the properties done for now (please feel free to add any should you feel I should need them though, why I am asking for your help ). Right here is my code, it is all on the same file, say class.db.php or something simple, just to see how I can get this working firstly, then I will segregate (or more split the new Db class into its own file), then have my actual form generation going from another class file and then do a real implement of the whole thing. Again this is only for my own education, nothing else! Here is my class file for the database: class Db { protected $_connect; // dont allow credentials in here yet! protected $_query; // holds the query info? protected $_error; // raises an error message when needed! public function __construct($host,$username,$password) { $this->_connect = mysql_connect($host,$username,$password); } } $newDatabase = new Db("localhost","dbuser","password"); echo "<pre>"; print_r($newDatabase); echo "</pre>"; What it's bringing up though is along the lines of this: Quote Db Object ( [_connect:protected] => Resource id #2 [_query:protected] => [_error:protected] => ) Is there any obvious error I am doing to not allowing the properties to fill up or something? I cant seem to get this working, again any helps appreciated, Jeremy. 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? Hi guys I need some help with slow connection to remote mysql database.
I've been after this for a couple of days. I've been reading around but I didn't find any solution which helped me. I have this scenario:
Server A e-commerce running mysql database running Server B e-commerce running remote connection to server A database The two e-commerce are identical. On server A it runs very quick, on server B the connection to mysql database it's about 16 times slower. Some complex queries and mixes queries don't get resolved and let the page go in timeout. I tried a test php script where I connect to mysql and I run a simple query (some classes are required before the query). On server A execution time is 0.107 seconds while on server B it is 1.788 seconds. I tried to have the same test with both firewall (server A and B) turned off but the results is exactly the same. I added in my.cnf of server A skip-name-resolve and restarted mysql but this didn't really change anything I am logging slow queries and none from server B are recorded in the file Running the same query from remote ssh connection from server B to server A's mysql is very fast Connection is set to persistent on server B's e-commerce Both server have centos 6.2 installed with WHM/Cpanel, configurations are basically the same. Do I miss something obvious? Alright, first off, I'm fairly new to this aspect of web design. While I have been messing around and designing sites using your basic HTML/CSS/Flash for some time, I've decided to get into the more serious aspects of web design. As of right now, I'm using a fairly basic webhosting service that doesn't give me full administrative permission to MySQL because, as far as I can tell, the databases reside under their super-database and not on your actual allotted server. This creates a problem with creating a true MySQL database in which you set up users for their given tables you want them to be able to edit. Let me remind you here again that I am faily new to this aspect of web design, so maybe no one actually runs their databases in this way. My work around is to have the first table be the user/password table and only have a singular script that I call up every time my forms need to modify a table. I hide this small connection script in the root folder of my server where it is not viewable and just call it into my php scripts using 'include()' or 'get_file_contents.' What I'm asking here I guess is if this method is secure? And if anyone has any other ideas as to how to go about creating this database. Thanks in advance! Hi, So as you might (or might not) have guessed I need to open/close new connections inside my functions. Here's my current code: Code: [Select] <?PHP /** * This function checks the ban status of the account. * @return 1 if banned */ function checkBan() { mysql_close($con); require("./includes/wow.php"); $result = mysql_query("SELECT * FROM wow_logon.accounts WHERE forum_acc= '.$user->data['user_id'].'"); $row = mysql_fetch_array($result); if($row["banned"] == "1") { return 1; $ban_reason = $row["banreason"]; } //$user->data['user_id'] mysql_close($connect); require("./includes/config.php"); } ?> When trying to use the function: checkBan(); if(checkban() == "1") { echo'function works, and returns 1. Ban reason: '.$ban_reason.' '; } This gives a pretty good idea of what I try to accomplish I hope, if not, an explanation is below. This code unfortunately returns: Code: [Select] [phpBB Debug] PHP Warning: in file /home/fusion/public_html/includes/functions_user.php on line 9: mysql_close() expects parameter 1 to be resource, null given [phpBB Debug] PHP Warning: in file /home/fusion/public_html/includes/functions_user.php on line 12: mysql_fetch_array() expects parameter 1 to be resource, boolean given [phpBB Debug] PHP Warning: in file /home/fusion/public_html/includes/functions_user.php on line 9: mysql_close() expects parameter 1 to be resource, null given [phpBB Debug] PHP Warning: in file /home/fusion/public_html/includes/functions_user.php on line 12: mysql_fetch_array() expects parameter 1 to be resource, boolean given Line 9 & 12: mysql_close($con); $row = mysql_fetch_array($result); Explanation: What I want to do is that I have a user account panel. When the user log in, I want to call a function to check if the user is banned. If the user is banned then we have returned 1, and display some banned message, followed by the ban reason. P.S. is it possible to use stored variables inside a function? When I do this, I connect to another sql server, by first closing the existing connection (if any) and open a new one to execute my statements. Then close that connection and resume the old one. |