PHP - Checking If The Mysql Database Connection Is Working?
Is there an alert method for the MySQL database or something similar?
What is the proper way to check if the MySQL database connection is working?
I mean other than "creating" and "retrieving" with "insert" and "select".
Similar TutorialsThe Script:
pdo_connect.php:
<?php $dsn = "mysql:host=localhost;dbname=2354"; $db = new PDO($dsn, "root", ""); ?>pdo_test.php: <?php try{ require_once("pdo_connect.php"); }catch(Exception $e){ $error = $e->getMessage(); } ?> <!DOCTYPE html> <html> <head> <title>Database Connection with PDO</title> </head> <body> <h1>Connection with PDO</h1> <?php if($db){ echo "<p>Connection successful.</p>"; }elseif(isset($error)){ echo "<p>$error</p>"; } ?> </body> </html>I have just watched a tutorial and tried out this script. The issue is that I am getting the following notice alongside with the error message: Notice: Undefined variable: db in C:\xampp\htdocs\oophp\pdo_test.php on line 18 SQLSTATE[HY000] [1049] Unknown database '2354'By the way this notice does happen in the tutorial as well. My question is: How to have this in ways, where the notice does not occur? 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. 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? Hey I'm trying to check a row in my database to see if its empty but this isnt working $usercheck = mysql_query("SELECT pet FROM users where name='$user'"); $returned_rows = mysql_num_rows($usercheck); if ($returned_rows == 0){ // do stuff if no pet }else{ echo 'There was ' . $returned_rows . ' records found.'; } The problem is its not checking the row pet its just checking to see if anything exists my database has id name pet 1 joe <empty> its just seeing joe and echoing "there was 1 record found" instead of seeing that the row pet is empty. thanks for the help after cloasing connection of database i still got the values form database. Code: [Select] <?php session_start(); /* * To change this template, choose Tools | Templates * and open the template in the editor. */ require_once '../database/db_connecting.php'; $dbname="sahansevena";//set database name $con= setConnections();//make connections use implemented methode in db_connectiong.php mysql_select_db($dbname, $con); //update the time and date of the admin table $update_time="update admin set last_logged_date =CURDATE(), last_log_time=CURTIME() where username='$uname'limit 3,4"; //my admin table contain 5 colums they are id, username,password, last_logged_date, last_log_time $link= mysql_query($update_time); // mysql_select_db($dbname, $link); //$con=mysql_connect('localhost', 'root','ijts'); $result="select * from admin where username='a'"; $result=mysql_query($result); mysql_close($con); //here i just check after closing data baseconnection whether i do get reselts but i do, why? echo "after the cnnection was closed"; if(!$result){ echo "cont fetch data"; }else{ $row= mysql_fetch_array($result); echo "id".$row[0]."usrname".$row[1]."passwped".$row[2]."date".$row[3]."time".$row[4]; } // echo "<html>"; //echo "<table border='1' cellspacing='1' cellpadding='2' align='center'>"; // echo "<thead>"; // echo"<tr>"; // echo "<th>"; // echo ID; // echo"</th>"; // echo" <th>";echo Username; echo"</th>"; // echo"<th>";echo Password; echo"</th>"; // echo"<th>";echo Last_logged_date; echo "</th>"; // echo "<th>";echo Last_logged_time; echo "</th>"; // echo" </tr>"; // echo" </thead>"; // echo" <tbody>"; //while($row= mysql_fetch_array($result,MYSQL_BOTH)){ // echo "<tr>"; // echo "<td>"; // echo $row[0]; // echo "</td>"; // echo "<td>"; // echo $row[1]; // echo "</td>"; // echo "<td>"; // echo $row[2]; // echo "</td>"; // echo "<td>"; // echo $row[3]; // echo "</td>"; // echo "<td>"; // echo $row[4]; // echo "</td>"; // echo "</tr>"; // } // echo" </tbody>"; // echo "</table>"; // echo "</html>"; session_destroy(); session_commit(); echo "session and database are closed but i still get values from doatabase session is destroyed".$_SESSION['admin']; ?> session is destroyed but database connection is not closed. thanks Hi everyone, I have been trying to get this code working but no matter what I try it will not work, I am trying to allow a user to update their personal details when they login to my website. I have created a form and submit button, the code is shwn below: <?php echo $_SESSION['myusername']; ?> <br><br> <form action="updated.php" method="post"> Firstname: <input type="text" name="firstname" /><br><br> Surname : <input type="text" name="surname" /><br><br> Date Birth: <input type="text" name="dob" /><br><br> Total Wins: <input type="text" name="wins" /> Total Loses: <input type="text" name="loses" /><br><br> Email Add: <input type="text" name="email" /><br><br> Country : <input type="text" name="born" /><br><br> Other Info: <input type="text" name="other" /><br><br> <input type="submit" name="Submit" value="Update" align="right"></td> </form> The updated.php file <?php mysql_connect ("localhost","root","") or die("Cannot connect to Database"); mysql_select_db ("test"); $sql=mysql_query("UPDATE memberdetails SET firstname='{$_POST['firstname']}', surname='{$_POST['surname']}', dob='{$_POST['dob']}', totalwins='{$_POST['wins']}', totalloses='{$_POST['loses']}', email='{$_POST['email']}', country='{$_POST['born']}', info='{$_POST['other']} WHERE username=$_SESSION['myusername']); if (!mysql_query($sql)) { die('Error: ' . mysql_error()); } echo "Details Updated"; ?> This is the error i recieve: Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in C:\wamp\www\website\updated.php on line 45 Line 45 is $sql=mysql_query line If anybody can help it will be very much appreciated! Hi, this is my first post:) pretty sure i will be posting here in the future. Anyway i am having trouble with a php script which downloads a file from a mysql database. This php script works for text files and should work for most files from what i understand. When downloading a text file, the whole file is downloaded from the server. When downloading an mp3 file, only 16kb are downloaded and the file does not play. When looking at the data in the database, it displays that the full file is there (correct amount of bytes, so there is nothing wrong with my upload php script). Does anyone have any suggestions as to what I can change to make this work? Code: [Select] <?php if(isset($_GET['id'])) { // if id is set then get the file with the id from database $link=mysql_connect('localhost', 'root', ''); @mysql_select_db('filemgr') or die ("<p>Could not connect to mysql!</p>"); $id = $_GET['id']; $query = "SELECT name, type, size, content " . "FROM upload WHERE id = '$id'"; $result = mysql_query($query) or die('Error, query failed'); list($name, $type, $size, $content) = mysql_fetch_array($result); header("Content-length: $size"); header("Content-type:$type"); header("Content-Disposition: attachment; filename=$name"); echo $content; mysql_close($link); exit; } ?> I wish to have a page that will display a form if there aren't already enough registrations in the database. The following it an outline of how it will be: <?php require_once "../scripts/connect_to_mysql.php"; //this works fine // Count how many records in the database (1) $sqlCommand = "SELECT * FROM teams"; (2) $sqlCommand = "SELECT COUNT (*) FROM teams"; (3) $sqlCommand = "SELECT COUNT (id) FROM teams"; $query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error()); (1) $numRegistrations = mysql_num_rows($query); //Count how many rows are returned from the query above (2) $numRegistrations = $query (3) $numRegistrations = mysql_num_rows($query); mysqli_free_result($query); ?> (Some HTML code, like DOCTYPE, head, start of body tags) <?php if($numRegistrations > 35){ echo "Sorry, registrations for this event is at it's maximum."; }else{ ?> <form blah blah blah> </form> <?php } ?> (end of body and html tag) You'll see above there is (1), (2), (3). These are the main 3 that I've been trying, and they match up the $sqlCommand to the $numRegistrations. What would be the problem with this code? I use wamp server to test, have been using it for ages. Chrome browser to test in. If I remove the database query, the rest of the page will load. With the query in there, only the HTML code up until the database query is parsed, so therefore nothing is display on the page. Please help. Thanks Denno On some occasions I need to connect to a second and third database in the same script (maybe 5% of scripts have at least a second connection). Usually I would just select the new database. However, my host requires different users to be created for each database. What is the best way to do this? Close current connection (say db1) and open new (say db2) OR keep all open, creating 2nd and 3rd connections. I am happy with the design of my database, and don't want to merge all these tables into one db. Overall I am still happy with my host, so I'd rather not change. <?php class UserQuery { public function Adduser($id,$username,$email,$password) { $conn = new Config(); $sql =("INSERT INTO test.user (id, username, email, password) VALUES ('$id', '$username', '$email',$password)"); $conn->exec($sql); } }
getting an "exec doesnt exist " error, saying exec doesnt exist in my db file. it doesnt need to exist does it ? anyone any idea why ?
hey i need help im tryig to get information from my user and then process it in my database so i can use it to log them to a different web site im trying to use this method to get the information from the user but need help to get it please help me. Code: [Select] //make the database connection. $conn = mysql_connect("localhost", "Black Jack"); mysql_select_db("chaper7", $conn); //create a query $sql = "SELECT * FROM hero"; $result = mysql_query($sql, $conn); I get the following error when trying to connect Warning: mysql_connect() [function.mysql-connect]: Can't connect to MySQL server on '72.18.129.104' (10061) in C:\Domains\crysvis.com\wwwroot\include\dbConnectAndSelect.php on line 8 Here's the code $host = "72.18.129.104"; $user = "deltron"; $pass = "masterconn"; $db = "customers"; $conn = mysql_connect("$host","$user","$pass"); if(!$conn) errorHandler("Msg 10:\nCould not connect to database with $host,$user,$pass in ". $_SERVER["PHP_SELF"]."\nCustId = $CustId\nmysql_error() = ".mysql_error()); if(!mysql_select_db("$db",$conn)) errorHandler("Msg 11:\nCould not select db=$db in ". $_SERVER["PHP_SELF"]."\nCustId=$CustId\nmysql_error() = ".mysql_error()); ?> What am I doing wrong? Any help will be appreciated how do I use a connection file (connection.php) in multiple programs? I think include? When you open a database connection, how long does it stay open for? I have a "Change E-mail Address" script that has 4 queries in it, and I just realized that I don't create a DB Connection until Query #2 in my script, yet things work fine?! Is it possible that the DB Connection was opened earlier by another script and it is just persisting?? Debbie I'm connecting to my database using the following... @ $db = new mysqli('host', 'username', 'password', 'database') The .php file that is connecting to the database is in my root (htdocs) folder on the server. I know that I am not supposed to put my actual 'host', 'username', 'password', 'database' inside the mysqli function for security purposes. I know that I am supposed to put variables in instead. But here is where I am confused. Where do I set those variables? Do I set them in another file and include that file? If so, where do I store the file that holds the passwords, and what prevents a hacker from simply navigating to that file? Thanks for the help Hi guys, Dear friends i,m a php beginner and i got a problem with connecting to my database i created a database called (koora) with one table called (admins) and when i tried to connect to it (database ) ; it did not connect here is the code i used for that <?php $connectdb = mysql_connect('localhost','','') or die("not connected"); $selectdb = mysql_select_db("koora", $connectdb); if(!$selectdb) { die("error connecting table" .mysql_error()); } then when refreshing my phpmyadmin page i got that message error connecting tableAccess denied for user ''@'localhost' to database 'koora' koora is the name of the database so i need your help with this problem and what is the reason not to connect to the data base Thank you |