Wednesday, March 2, 2011

determine if a mysqli query failed or not in php ?


Hello.
I have changed some of my old queries to the Mysqli framework to improve performance. Everything works fine on localhost but when i upload it to the webserver it outputs nothing. After connecting I check for errors and there are none. I also checked the php modules installed and mysqli is enabled.
I am certain that it creates a connection to the database as no errors are displayed. (when i changed the database name string it gave the error)
There is no output from the query on the webserver, which looks like this:
$mysqli = new mysqli("server", "user", "password");

if (mysqli_connect_errno()) {
   printf("Can't connect Errorcode: %s\n", mysqli_connect_error());
   exit;
}

// Query used
$query = "SELECT name FROM users WHERE id = ?";

if ($stmt = $mysqli->prepare("$query"))
{

    // Specify parameters to replace '?'
    $stmt->bind_param("d", $id);

    $stmt->execute();

    // bind variables to prepared statement
    $stmt->bind_result($_userName);

    while ($stmt->fetch())
    {
          echo $_userName;
    }


    $stmt->close();
 }
}

//close connection
$mysqli->close();
As I said this code works perfectly on my localserver just not online. Checked the error logs and there is nothing so everything points to a good connection. All the tables exists as well etc. Anyone any ideas because this one has me stuck! Also, if i get this working, will all my other queries still work? Or will i need to make them use the mysqli framework as well? Thanks in advance.
1 down vote
Each call to a mysqli/stmt method can fail. You should check each and every one.
Try it with error_reporting(E_ALL) and maybe display_error=On
error_reporting(E_ALL); ini_set('display_errors', 1);

// passing database name as fourth parameter
$mysqli = new mysqli("server", "user", "password", 'dbname');
if (mysqli_connect_errno()) {
   printf("Can't connect Errorcode: %s\n", mysqli_connect_error());
   exit;
}

// Query used
$query = "SELECT name FROM users WHERE id = ?";

if ( false===($stmt=$mysqli->prepare("$query")) ) {
  echo 'mysqli::prepare failed: ', htmlspecialchars($mysqli->error);
  die;
}

// Specify parameters to replace '?'
$rc = $stmt->bind_param("d", $id);
if ( !$rc ) {
  echo 'bind_param failed: ', htmlspecialchars($stmt->error);
  die;
}

echo '
Debug: execute()
';
$rc = $stmt->execute();
if ( !$rc ) {
  echo 'execute failed: ', htmlspecialchars($stmt->error);
  die;
}

echo '
Debug: bind_result()
';
// bind variables to prepared statement
$rc = $stmt->bind_result($_userName);
if ( !$rc ) {
  echo 'bind_result failed: ', htmlspecialchars($stmt->error);
  die;
}

echo '
Debug: fetch()
';
while ($stmt->fetch())
{
  echo 'username: ', $_userName;
}
echo '
Debug: stmt close()
';
$stmt->close();

echo '
Debug: mysqli close()
';
$mysqli->close();

No comments:

Post a Comment