-4

I'm using a sql database backup script, in a part of the code I have :

if (!isset($table_select))
{
$result = $dbc->prepare("show tables");
$i=0;
$table="";
$tables = $dbc->executeGetRows($result);
foreach ($tables as $table_array)
{
list(,$table) = each($table_array);
$exclude_this_table = isset($table_exclude)? in_array($table,$table_exclude) : false;
if(!$exclude_this_table) $table_select[$i]=$table;
$i++;
}
}

I dont know how to get rid of this part : list(,$table) = each($table_array);

As each() is deprecated, Does anyone know a solution?
Thank you so much!

Aska
  • 3
  • 4

2 Answers2

1

Since you're not using the key that each provides, it isn't needed in this context.

Example: https://3v4l.org/8vie4

As arrays are passed by-copy instead of by-reference, you can use array_shift() as an alternative if you are not using $table_array again in the same context.

foreach ($tables as $table_array) {
    $table = array_shift($table_array);
    var_dump($table);
}

Keep in mind array_shift retrieves the current value, and removes it from the array.

Since each() retrieves the current key value pair and advances the pointer to the next value, you can replace it with current() and next().

foreach ($tables as $table_array) {
    $table = current($table_array);
    var_dump($table);
    next($table_array);
}

If you do need the key of the current value when using current and next you can use key()

foreach ($tables as $table_array) {
    $key = key($table_array);
    $table = current($table_array);
    var_dump($key, $table);
    next($table_array);
}

Since the auto backup script you are using utilizes PDO, you can reduce the complexity by using fetchAll(PDO::FETCH_COLUMN); instead of executeGetRows Which will retrieve a flat array of the 0 indexed column as opposed to the column key value pair.

$result = $dbc->prepare("show tables");
$result->execute();
$i=0;
$table="";
$tables = $result->fetchAll(\PDO::FETCH_COLUMN);
foreach ($tables as $table) {
     //...
}
Will B.
  • 14,243
  • 4
  • 56
  • 62
  • Thanks you so much. You are my super hero. Works like a charm. thanks you so much for you kindness. – Aska Oct 20 '18 at 19:26
  • @Aska if you believe my answer resolved your issue, please upvote it or mark it as the accepted answer, so others know that your issue no longer needs an answer. – Will B. Oct 20 '18 at 22:38
0

You dont't want to do that within a php script. I strongly recommend to use some cronjob for this task, as far as that is possible for you.

You could create a cronjob using

crontab -e

And add something like:

0 1 * * * mysqldump -e --user=username --password='password' dbname | gzip | uuencode
sql_backup.gz | mail example@example.com

The above example would fire up the job every day at 01 AM.

You can checkout the manual here.

Hope that helps! :)

errorinpersona
  • 310
  • 4
  • 14