Retry on database exception using php

I have been working on exceptions thrown by php - mysqli & created this snippet below that tries to check a few times to see if a temp glitch has caused the database to fail. if so, it tries to recover. If it cannot then it quits/ ends.

Now while the logic is fine, I cannot find out why the echo statements do not occur at regular intervals as they should. Only towards the end (depending upon how the exception is thrown in the findMail() function), the output is spewed & correctly so. The throw new exception line can be changed to fail at all times or to pass the last time around. It is set to pass the last time round in the snippet. Would be great if someone can point to me why the echo is not displaying the output as it should at intervals.

Further I am not sure if this is a good or a bad idea in production. Any feedback on this is very welcome. Thanks to all.

The code Snippet:

<?php $host = 'localhost'; $user = 'root'; $password = ''; $database = 'test'; // OPEN A CONNECTION TO THE DATA BASE SERVER AND SELECT THE DB try { $con = new mysqli($host,$user,$password,$database); if($con->connect_error) { throw new Exception("Goof Up"); } mysqli_set_charset($con, "utf8"); } catch(Exception $e) { echo $e->getMessage(); exit; } // All well so far $cnt = 0; if(findMail($con,$cnt)) echo "<br> Hurray !!"; function findMail($con,$cnt) { try { echo $cnt++."<br>"; $query = "SELECT name, email from users"; $stmt=$con->prepare($query); if($cnt < 3 ) throw new exception($cnt); if($stmt->execute()) { $stmt->bind_result($name, $email); while ($stmt->fetch()) { $email = htmlspecialchars($email); $name = htmlspecialchars($name); echo $name.' ---- '.$email.'<br>'; } } } catch(Exception $e) { $cnt = (int)($e->getMessage()); // echo $cnt; if($cnt === 4) { echo "Ending"; exit();} sleep(5); findMail($con,$cnt); } return true; } ?>

--------------Solutions-------------

It must have something to do with browser rendering while using ob_start and ob_flush under certain conditions.

I noticed when i set php header("Content-Encoding: none") to disable gzip compression:

UPDATE - added an example

<?php
header("Content-Encoding: none");

ob_end_clean();
ob_start();

for($i=0;$i<5;$i++)
{
echo 'No. '.$i."<br>";
ob_flush();
flush();
sleep(2);
}
?>

it flushes properly. Check out more details on the below links

PHP Streaming/Output Buffering no longer working

For php flush - how to disable gzip for specific file?

Using this PHP script with sleep(X) can cause the user to wait until its complete (successfully or not).

I recommend to call the script through AJAX (E.g. jQuery.ajax([...])), so the frontend is not blocked.

UPDATED - Example of using ajax instead

File: test.php

<?php
// verify if this is an ajax request (if, so exit the script before out)
if(isset($_GET['ajax'])) {

$host = 'localhost';
$user = 'root';
$password = '';
$database = 'test';

// return result being parsed by JS through json_encode
$result = array('data' => null, "error" => false);

/**
* function to return name and emails as array list
*/
function findMail($con)
{
$data = null;
$query = "SELECT username, uid from tbl_user";
$stmt=$con->prepare($query);
if($stmt->execute())
{
$data = [];
$stmt->bind_result($name, $email);
while ($stmt->fetch())
{
$email = htmlspecialchars($email);
$name = htmlspecialchars($name);
$data[] = array('name' => $name, 'email' => $email);
}
}
return $data;
}

try
{
$con = new mysqli($host,$user,$password,$database);
if($con->connect_error)
{
throw new Exception("Goof Up");
}
mysqli_set_charset($con, "utf8");

$result['data'] = findMail($con);
}
catch(Exception $e){
$result['error'] = true;
}

echo json_encode($result);
exit;
}
?>
<!DOCTYPE>
<head>
<title>TEST 1</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">

$(function(){
var retryCounter = 0;
var repeatInterval = 3000;
var repeatCall = function(){
if(retryCounter >= 3) {
console.log('max retries reached');
return;
}
console.log('Calling...');

$.ajax({
url: "test.php?ajax=1",
dataType: "json"
})
.done(function( result, textStatus, xhr ) {
// data = the json encoded result from errScript.php
console.log("received data from errScript.php");

if(!result) {
console.log('STOPPED due to invalid/empty data');
return;
}

// on error, retry and increase counter
if(result.error)
{
setTimeout(repeatCall, repeatInterval);
retryCounter++;
return;
}

$.each(result.data, function(k, v){
document.write(v.name + " --- " + v.email + "<br />");
});
}).fail(function(xhr, textStatus, err) { console.log('error'); });
};

setTimeout(function() { repeatCall(); }, repeatInterval);
});

</script>

</head>
<body>
<h1> TEST 1 </h1>
</body>
</html>

Category:php Time:2019-01-02 Views:8

Related post

  • How to convert database foxpro (.dbf) file to sqlite database file using PHP scrpit? 2011-08-04

    I am trying to convert database foxpro (.dbf) file to sqlite database file using PHP scrpit.. Please help me to convert the dbf files to sqlite files or provide suggestion for conversion. Thank you in advance... --------------Solutions------------- C

  • how to import the excel data to the mysql database or using PHP? 2011-11-04

    the data base data is stored as the image shows. the table is products. the data in excel is as the following shows. but when i open it by notepad++. it shows like this: 1, the data's format which i prepared is right? if not? how to correct it? suppo

  • how do I know the data type of database field using PHP,.? 2011-11-11

    I want to know how I can get the datatype of each field in a SQL database using PHP; I want use this datatype for creating some docs in SOLR. For Example: if (datatype == int) then "[field_name] + _i". So, if I have field bedrooms and the datatype is

  • Using OnClick event of Anchor Tag Retrieved Database Data using php 2011-12-22

    I want that if i click on an anchor tag it shows the mysql database table values for example <a href"#">Click to show comments</a> after clicking it will do something like this SELECT * FROM `comments`LIMIT 0 , 30 --------------Solutions-

  • Possible to restore MSSQL Backup to different database name using PHP PDO? 2012-04-13

    Is it possible to restore MSSQL Express Backup file to a different database name on another server running MSSQL Server using only PHP PDO and FTP access? --------------Solutions------------- You can't do it without a copy of the database first. Use

  • continuously checking data in mysql database and using php 2012-03-06

    I'm working on a system using php and mysql. It currently has a working sms feature which supports sending messages to users and receiving the messages sent by users. All sent and reveived messages are stored in different tables (one for sent and ano

  • How can I do search efficiently data in Database except using fullsearch 2009-02-13

    I want to search a sentence (word combination of) in some table or view of DB. I dont want to use Fultext search property of DB. Is there any alternative efficient way? --------------Solutions------------- Without the use of an index, a database has

  • Insert variables and arrays in different database tables using PHP and MySQLi 2009-03-07

    I'm learning PHP and MySQL and I'm creating a movies website for learning purposes. I want to insert variables and arrays containing movie info into a database but in different tables. This is what I have right now: include('inc/connection.php'); $co

  • Storing multiple tags in a MySQL database problem using PHP/MySQL? 2009-12-06

    First let me explain that I have this script that should let users enter multiple tags that are separated by a comma for example, shoe, shirt, hat, glasses and store each tag in the database. But for some reason the tags are not being stored in the d

  • Tracking database usage using php and Mysql 2010-01-12

    I am designing a php mysql webapp. In that, a database usage log has to be maintained , which will record 1.User ip 2.Timestamp 3.operation performed(Add,edit or delete) 4.Colmns changed 5.rowid 6.old value 7.new value Please suggest any example scri

  • How do you get the glyph for a character encoded as 'ō' from a utf-8 encoded database field using php? 2010-04-22

    I have a MySQL database table with a collation of 'utf8_general_ci' and the value in the field is: x & #299; bán yá wén (without the spaces). When this is converted (for example by StackOverflow's editor) it looks like this: xī bán yá wén where t

  • How to display the random images without repetition from database(MySql) using php 2010-06-26

    I have a program in php that should display the random images without repetition,I was able to store the images in the database, but I don't have any idea to do this can anyone help me with this. Thank you, --------------Solutions------------- Save w

  • Basic update database table using php question 2011-05-17

    I seem to be missing something quite fundamental here and yet my code doesn't seem to be any different to any of the numerous online tutorials that I have looked at. What I would like is for someone to look at this and say....Oh you have forgotten to

  • How do I change the database values using PHP and MySQL? 2011-08-12

    I have user table having fields gender and first name like this.. The value stored in the database for gender type is 0 for M(Male) and 1 for F(Female). I am retrieving the details from database. By using the following query and displaying the detail

  • Database query using PHP 2012-02-18

    I'm new here.. I just want to ask on how to compare a user input from the value taken from the a specific table in the database.. Like for instance.. I have a table named sample which has 3 fields namely ID, WebsiteName, IpAddress.. Sample value: 1 w

  • Database merge using PHP MyAdmin 2012-03-14

    I have two database ms1 and ms2 with same fields and same tables. i want to merge both data from ms1 to ms2. as i have same primary keys. Anybody have idea? --------------Solutions------------- Follow steps stated by @Sevak. Export db2 table with str

  • How to store selected radio buttons on each page into database accordingly using PHP? 2012-03-18

    Given this table in my database: |AnswerID|QuestionID|AnswerText| |21 |2 |User | |22 |2 |Admin | |23 |2 |Guest | |24 |2 |User2 | I have created a quiz using PAGINATION to display individual question and its options on each of the page. Example code s

  • How to display multiple cell entries individually from a MySQL database and using PHP 2010-03-22

    I have a column called post_tags where there is sometimes one tag entry and sometimes multiple tags stored. These are separated by * symbols. I want to display these out to the screen one by one. If there were just one item inside the cell I would ha

  • MySQL database restore using PHP 2011-05-06

    I'm trying to restore MySQL dump created the following way: $file = '/path/to/file.sql'; exec('mysqldump -u '.DB_USER.' -p'.DB_PASS.' '.DB_NAME.' > '.$file); the above creates the dump as expected, then to restore I'm trying to use the following:

  • How can we detect the update or insertion in database table using php? 2011-12-07

    A database table's been updated by a person A with status_id,status_text,timedate etc (like facebook status). Another person B comments on that status, Both persons A and B are online. How would person A will be notified(like in facebook). Means how

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 1.523 (s). 13 q(s)