2

I recently learned that mysql_* has been depreciated and i have a quick question on how to rewrite something.

$db = mysql_connect("localhost","root","PASSWORD");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("FormData" ,$db);

I have tried rewriting it like this...

$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData", $db);
if(!$db) die("Error connecting to MySQL database.");

But when it posts my form i get the "Error connecting to MySQL database." error. I was able to fix it by just using this but i wanted to know how to add in the Error connecting.

$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData");

Any help would be great as i try to learn all of the new MySQLi stuff!

2
  • Since you have a solution which could contain an error, try using a wrong password and see if it will die. It seems to be a logical error. Commented Aug 21, 2013 at 21:08
  • 1
    Strangely, but you accepted the only wrong answer. Commented Aug 21, 2013 at 21:17

4 Answers 4

3

PHP website

Straight from php.net

<?php
$mysqli = new mysqli('localhost', 'fake_user', 'my_password', 'my_db');

// Works as of PHP 5.2.9 and 5.3.0.
if ($mysqli->connect_error) {
    die('Connect Error: ' . $mysqli->connect_error);
}
?>

Edit:

The below will also allow you to do it your way.

$mysqli = mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');

Then you can:

if (!$mysqli) {
   //handle the error
}

Consider PDO if possible. They are kind similar to me.

Sign up to request clarification or add additional context in comments.

7 Comments

Please don't use the error suppression operator, see here for an explanation: error suppression operator
Ooops... Sorry... Let me remove it. I realise what you mean.
However, -1 for die(). In 21th century we have some more intelligent ways to handle an error message, throwing an exception for example.
@YourCommonSense I don't really care how the error is handled. Everyone has their own way. Modifications can be made. I just answered the question. How the error is handled is up to them. But yeah... Throwing an exception will do too.
Yeah, that's the problem with this site. Nobody cares. Even if your second part won't work with modern PHP versions
|
2
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData", $db);
if(!$db) die("Error connecting to MySQL database.");

should be

$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData");
if($mysqli->connect_error) die("Error connecting to MySQL database.");

the parameters for mysqli() are:

[ string $host = ini_get("mysqli.default_host") [, string $username = ini_get("mysqli.default_user") [, string $passwd = ini_get("mysqli.default_pw") [, string $dbname = "" [, int $port = ini_get("mysqli.default_port") [, string $socket = ini_get("mysqli.default_socket") ]]]]]]

Not sure why you were trying to use the $db variable to set the port for the connection and then checking if the port variable is true...

For future reference the best place to look first, would be the docs

EDIT

As @Touch pointed out, you must check if error exists and not just that object exists. Edited code to reflect this.

3 Comments

I will comment and say that @Touch has a better total solution as it will give you the exact error from mysqli. However, this answer solves what you were doing wrong.
Are you sure this will return the right result? What if you can create a new object that doesn't have a connection? Or is that no possible?
Just tested your solution on my PHP. It won't work because there will be an object but there will be no way to know if there is a connection or not. And the ! will only test if there is an object and not if there is a connection. I think it's best stick to the tried and tested. It's more of a lofical error to me.
0

Using mysqli:

define('DB_HOST', 'localhost');
define('DB_NAME', 'some_database_name');
define('DB_USER', 'some_user');
define('DB_PASS', 'some_password');


$Connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (!$Connection->connect_errno) 
{
  //do your prepared stuffs
}
else
{
  die("Database Connection error:".$Connection->connect_error);
}

or using PDO

try 
{
  $PDOConnection = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'', DB_USER, DB_PASS);
  $PDOConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  //do your prepared stuffs

  $PDOConnection = null;
} 
catch(PDOException $e) 
{
  die('ERROR: ' . $e->getMessage());
}

Comments

0

I wrote a class called better_mysqli that extends mysqli making it easier to use.

The following example shows the answer to your question and also shows basic usage of the better_mysqli class. You can view a detailed example with lots of comments here: detailed usage of better_mysqli

<?php

  include_once('better_mysqli.php');  // can be obtained from: http://pastebin.com/ATyzLUfK

  // THIS NEXT PART ANSWERS YOUR QUESTION 
  // THIS NEXT PART ANSWERS YOUR QUESTION 
  // THIS NEXT PART ANSWERS YOUR QUESTION 

  // THE ONLY DIFFERENCE IN THE CONNECTION WHEN USING better_mysqli AND mysqli
  // is $mysqli = new better_mysqli(...)  and $mysqli = new mysqli(...) 

  // == Instantiate the mysqli database object (aka open the database) ==
  $mysqli = new better_mysqli('your_server', 'your_user', 'your_pass', 'your_db_name');
  if (mysqli_connect_errno()) {
     error_log(sprintf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error()));
     exit;
  }


  // == select example ==
  unless( $sth = $mysqli->select('select * from table1 where col1=? and col2=?', $row, array('col1_placeholder_value', 'col2_placeholder_value'), $debug_level=0, $verbose_debug_output)){
        if($debug_level>0){ echo $verbose_debug_output;}
        // .. do your error handling here
  }
  while($sth->fetch()){
          echo $row['col1'] .', '. $row['col2'] .', and '. $row['col_etc'] .' are accessed like that.<br>';
  }


  // == insert example ==
  $statement = "insert into table1 (col1, col2, date_col, col_etc) values (?, ?, NOW(), ?)";
  unless( $mysqli->insert($statement, array('col1_insert_value', 'col2_insert_value', 'col_etc_value'), $debug_level=0, $verbose_debug_output, $id_of_new_record) ){     
          if($debug_level>0){ echo $verbose_debug_output;}
          // .. do your error handling here
  }


  // == update example ==
  unless($mysqli->update("update table1 set col1=? where col2=?", array('col1_value', 'col2_value'), $debug_level=0, $verbose_debug_output) ){
          if($debug_level>0){ echo $verbose_debug_output;}
          // .. do your error handling here      
  }


  // == delete example ==
  unless( $mysqli->delete("delete from table1 where col1=? where col2=?", array('col1_value', 'col2_value'), $debug_level=0, $verbose_debug_output) ){
          if($debug_level>0){ echo $verbose_debug_output;}
          // .. do your error handling here      
  }


  // in all cases statements are prepared just once and cached so if you reuse any statement the already prepared statement handle is automatically used


?>

5 Comments

Why not just move to PDO?
@touch I wrote it before PDO
So I see - it looks quite outdated. With error handling code all over the place.
@YourCommonSense I have this code in many high volume production sites and still use it in ongoing projects without trouble. Most people complain that example DON'T show error handling so why the negativity?
yep. you indeed have this if($debug_level>0) in high volumes. instead of writing it only once, in a centralized error handling facility

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.