PHP checking mysql connection - php

I am building a project with installation (suck as WordPress) and the user provides database information (server, username, password and database). Now, I have to check if it can connect to the provided database. I tried this code, but it seems that it does not work (I am using Mysqli btw):
public function checkDataBaseConnection($server, $user, $pass, $db)
{
$conn = #mysqli_connect($server, $user, $pass, $db);
if(mysqli_connect_error())
{
return FALSE;
}
else
{
mysqli_close($conn);
return TRUE;
}
}
What other way can I use to check if the server can connect to the database?

One thing: Remove the #, that suppresses some php warnings.
Second thing: Try this:
public function checkDataBaseConnection($server, $user, $pass, $db)
{
$conn = #mysqli_connect($server, $user, $pass, $db);
if(!$conn)
{
return FALSE;
}
else
{
//mysqli_close($conn); why would you close the connection?
return $conn;
}
}

Have you tried something like this?
if (checkDataBaseConnection($server, $user, $pass, $db))
echo "Success!";
else
echo "Fail.";
By the way you just can do this way
mysqli_connect($server, $user, $pass) or die('Connection failed');

Well, if you look at the PHP page for mysqli_connect you can see this example:
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
/*
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
*/
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
/*
* Use this instead of $connect_error if you need to ensure
* compatibility with PHP versions prior to 5.2.9 and 5.3.0.
*/
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . $mysqli->host_info . "\n";
$mysqli->close();
?>

Related

convert mySQL to mySQLi - using a class

The previous programmer had used a class called database that has the connection string and a bunch of functions. I now have to convert this to MySQLi and I am at a loss.
class database {
var $sql='';
var $result='';
function database( $host='localhost', $user, $pass, $db) {
// perform a number of fatality checks, then die gracefully
if (!function_exists( 'mysql_connect' )) {
//or die( 'FATAL ERROR: MySQL support not available. Please check your configuration.' );
exit();
}
bla..bla..bla - bunch of code goes here
function get_events_by_user($username) {
$sql = "SELECT event_id FROM user_events WHERE username = '$username'";
$result = mysql_query($sql);
return $result;
}
}
I tried
var $link=mysqli_connect('localhost', $user, $pass);
to use as
$result = mysqli_query($link,$sql);
but I can not use expression as a variable value and I don't know what else to do.
Thanks a bunch! :)
try to use this.
I think it solves your problem.
<?php
$link = mysqli_connect("localhost", $user, $pass, $databaseName);
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
mysqli_set_charset($link, "utf8");
?>
just bring the $link in every query.
$link = mysqli_connect("localhost", $user, $pass, $db);
function get_events_by_user($username) {
$sql = "SELECT event_id FROM user_events WHERE username = '$username'";
$result = mysqli_query($link,$sql);
return $result;
}

PHP MySQL function dies

Ive written my function just to check if the database connection is working.
And it seems like he cant connect to my database, thats no problem, but he dies at the point where i run the function.
function testconnection() {
global $dbhost, $dbuser, $dbpassword, $dbname;
error_reporting(E_ERROR);
$conn = mysql_connect($dbhost, $dbuser, $dbpassword);
$dbconn = mysql_select_db($dbname);
if ( !$conn ) {
return "connfailed";
}
if ( !$dbcon ) {
return "dbconnfailed";
}
}
It stops any further building of the website.
All variables are defined. This function is just used to display an error message if it returns "dbconnfailed".
but even with echo testconnection(); it displays nothing.
can be seen here
but I host this at a big company and on localhost via xampp
it isnt working on one.com but it is working on xampp
You did not add your connection to $dbconn
$dbconn = mysql_select_db($dbname,$dbconn);
Pls Don't use the deprecated and insecure mysql_*-functions. They have been deprecated since PHP 5.5 (in 2013) and were completely removed in PHP 7. Use MySQLi or PDO instead
If you are using mysqli: Try this one..
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM usertable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
use mysqli library
function testconnection() {
global $dbhost, $dbuser, $dbpassword, $dbname;
error_reporting(E_ERROR);
$conn = mysqli_connect($dbhost, $dbuser, $dbpassword);
/* check connection */
if (mysqli_connect_errno()) {
return "connfailed " . mysqli_connect_error();
}
$dbconn = mysql_select_db($dbname);
if(!$dbcon) {
return "dbconnfailed " . mysqli_error($dbconn);
}
}

PHP Error Object of Class Could Not Be Converted to String

I am trying to create a PHP file that connects to a mysql database and inserts data into the database. I am getting these errors:
( ! ) Catchable fatal error: Object of class foo_mysqli could not be converted to string in ( ! ) Notice: Undefined variable: host in C:\wamp\www\final_kk.php on line 21
( ! ) Catchable fatal error: Object of class foo_mysqli could not be converted to string in C:\wamp\www\final_kk.php on line 21
Line 21 is the first line inside of the try. Any help would be appreciated. Thanks!
<?php
class foo_mysqli extends mysqli {
public function __construct($host, $user, $pass, $db) {
parent::__construct($host, $user, $pass, $db);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
}
}
$db = new foo_mysqli('localhost', 'root', '', 'users');
echo 'Success... ' . $db->host_info . "\n";
try {
$conn = new PDO("mysql:host=$host;dbname=$db;username=$user;password=$pass", $user, $pass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users (fname, lname,email,username,password,SSN) VALUES ('$fname', '$lname', '$email', '$uname', '$password', '$ssn')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$db->close();
?>
Okay....I made some changes based on the comments and my code now looks like this:
<?php
class foo_mysqli extends mysqli {
public function __construct($host, $user, $pass, $db) {
parent::__construct($host, $user, $pass, $db);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
}
}
$db = new foo_mysqli('localhost', 'root', '', 'users');
echo 'Success... ' . $db->host_info . "\n";
settype($host, "string");
settype($user, "string");
settype($pass, "string");
try {
$conn = new PDO("mysql:host=$host;dbname=$db, $user, $pass");
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users (fname, lname,email,username,password,SSN) VALUES ('$fname', '$lname', '$email', '$uname', '$password', '$ssn')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$db->close();
?>
This got rid of one of my errors however I still get
( ! ) Catchable fatal error: Object of class foo_mysqli could not be converted to string in C:\wamp\www\final_kk.php on line 33
please help...what am I doing wrong?
You're setting $db as an instance of a foo_mysqli() object in this line:
$db = new foo_mysqli('localhost', 'root', '', 'users');
Later in
$conn = new PDO("mysql:host=$host;dbname=$db;username=$user;password=$pass", $user, $pass);
you're using $db as a database name. It's enclosed in a double-quoted string, so PHP will attempt to interpolate it and substitute a string in the PDO connection string. Since $db is now an object, it fails.
It's not clear why you're setting up an object that extends MySQLi when you're later using a PDO object anyway.
Additionally, you haven't defined $host in the scope where you're setting up your PDO connection, so PHP reports that as undefined.
Since you know what the host and database names are you could just do this:
$conn = new PDO("mysql:host=localhost;dbname=users;", $user, $pass);

Connect to DB and Activites by OOP in PHP

Hi I am having some issues connecting to my DB using OO PHP. My script is below. I have been going at this for a while now. This is just a test script as I am fairly new to OOP. Please don't be harsh
class Database{
public $mysqli,
$host,
$username,
$password,
$db;
public function __construct($host, $username, $password, $db){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$mysqli = new mysqli($host, $username, $password, $db);
if (!$mysqli){
echo "error in connecting to database";
}
else{
echo "success in connecting to database";
}
}
public function query(){
$result = $mysqli->query("SELECT * FROM inventory");
if ($result) {
printf("Select returned %d rows.\n", $result->num_rows);
$result->close();
}
else{
echo "there is an error in query";
$result->close();
}
//echo "in query function";
}
}
Usage...
$DB = new Database('localhost', 'root', 'xxxx', 'yyyy');
$DB -> query();
Your main problem is that you aren't storing a value into your class' $mysqli property. You need to use $this->mysqli in your constructor and query method instead of $mysqli.
Secondly, this class adds nothing that the mysqli class doesn't already have. You might as well simply use
$DB = new mysqli('localhost', 'root', 'xxxx', 'yyyy');
if ($DB->connect_error) {
throw new Exception($DB->connect_error, $DB->connect_errno);
}
The problem is, you are accessing the class property without $this. The $mysqli should be in $this->mysqli in constructor function.
You are using mysqli property as Object of mysqli class.
Then you can use the query function of mysqli property object(In Database class) by $this->mysqli->query("SELECT * FROM inventory") in query function.
Updated Code:
<?php
class Database{
public $mysqli,
$host,
$username,
$password,
$db;
public function __construct($host, $username, $password, $db){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->mysqli = new mysqli($host, $username, $password, $db);
/* check connection */
if ($this->mysqli->connect_errno) {
printf("Connect failed: %s\n", $this->mysqli->connect_error);
exit();
} else {
echo "success in connecting to database";
}
}
public function query(){
$result = $this->mysqli->query("SELECT * FROM inventory");
if ($result) {
printf("Select returned %d rows.\n", $result->num_rows);
$result->close();
}
else{
echo "there is an error in query";
$result->close();
}
//echo "in query function";
}
}
$DB = new Database('localhost', 'root', 'xxxx', 'yyyy');
$DB -> query();
Try this:
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// Test if connection succeeded
if(mysqli_connect_error()){
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}

starting with mysql on an ubuntu server php

I am new to mysql but have recently tried doing some tutorials to advance my knowledge. Anyways I installed mysql on my ubuntu server as well as phpmyadmin. They both seem to work just fine, I created a database in phpmyadmin called "test" as well as a table called "teddy".
I put data into the table and I can clearly see it through phpmyadmin.
Now when I try accessing this database via a php script on my ubuntu server, nothing happens. Literally nothing. It reacts the same way as if I had a syntax error (a quick load with nothing displayed).
This is my code... If anyone knows where my mistake is it would be much appreciated.
Thank you
<?php
$username='root';
$password='***';
$database='test';
#$db= mysqli_connect('localhost', $username, $password, $database);
if (mysqli_connect_errno())
{
echo 'Error: Could not connect';
exit;
}
$query= "select * from test";
$result= $db->query($query);
$num_results= $result->num_rows;
echo $num_results;
?>
EDITED (based on drew 010)
Problem was the table was not called test but teddy so putting in this code worked.
"SELECT * FROM 'teddy'";
$db= new mysqli('localhost', $username, $password, $database);
if (mysqli_connect_errno())
{
echo 'Error: Could not connect';
exit;
}
$query = "SELECT * FROM 'teddy'";
$result = $db->query($query);
if ($result) {
$num_results = $result->num_rows;
echo $num_results;
} else {
echo "Query failed: {$db->error}\n";
}
?>
$result= $db->query($query); is probably returning false for some reason.
Try:
$query = "select * from teddy";
$result = $db->query($query);
if ($result) {
$num_results = $result->num_rows;
echo $num_results;
} else {
echo "Query failed: {$db->error}\n";
}
See http://www.php.net/manual/en/mysqli.query.php#refsect1-mysqli.query-returnvalues
I don't use mysql but I'm guessing because you're using mysqli_connect. Try mysql_connect instead
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
http://php.net/manual/en/function.mysql-connect.php
#$db= mysqli_connect('localhost', $username, $password, $database);
should be
$db= new mysqli('localhost', $username, $password, $database);

Categories