Guest User

Untitled

a guest
Jul 17th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. <?php
  2.  
  3. // change these settings
  4. $servername = 'localhost';
  5. $username = 'dbuser';
  6. $password = 'password';
  7. $db = 'database';
  8.  
  9. // connect
  10. $conn = new mysqli($servername, $username, $password);
  11. try {
  12. $conn = new PDO("mysql:host=$servername;dbname=$db", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET sql_mode="NO_ZERO_DATE"') );
  13. $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
  14. echo "Connected successfully";
  15. } catch(PDOException $e) {
  16. exit( "Connection failed: " . $e->getMessage() );
  17. }
  18.  
  19. // get all table names
  20. $stm = $conn->prepare('SHOW TABLES');
  21. $stm->execute();
  22. $table_names = array();
  23. foreach ( $stm->fetchAll() as $row ) {
  24. $table_names[] = $row[0];
  25. }
  26.  
  27. // for all tables
  28. foreach ( $table_names as $table_name ) {
  29. echo "\nRepairing table $table_name...\n";
  30.  
  31. // get the primary key name
  32. $stm = $conn->prepare( "show keys from $table_name where Key_name = 'PRIMARY'" );
  33. $stm->execute();
  34. $key_name = $stm->fetch()['Column_name'];
  35.  
  36. // get the primary key type
  37. $stm = $conn->prepare( "show fields from $table_name where Field = '$key_name'" );
  38. $stm->execute();
  39. $key_type = $stm->fetch()['Type'];
  40.  
  41. // if there is a primary key
  42. if ($key_name) {
  43. echo "Primary key is $key_name\n";
  44.  
  45. try {
  46. // if auto_increment was missing there might be a row with key=0 . compute the next available primary key
  47. $sql = "select (ifnull( max($key_name), 0)+1) as next_id from $table_name";
  48. $stm = $conn->prepare( $sql );
  49. echo "$sql\n";
  50. $stm->execute();
  51. $next_id = $stm->fetch()['next_id'];
  52.  
  53. // give a sane primary key to a row that has key = 0 if it exists
  54. $sql = "update $table_name set $key_name = $next_id where $key_name = 0";
  55. echo "$sql\n";
  56. $stm = $conn->prepare( $sql );
  57. $stm->execute();
  58.  
  59. // set auto_increment to the primary key
  60. $sql = "alter table $table_name modify column $key_name $key_type auto_increment";
  61. echo "$sql\n";
  62. $stm = $conn->prepare( $sql );
  63. $stm->execute();
  64.  
  65. } catch (PDOException $e) {
  66. echo "\n\nQuery: $sql\nError:" . $e->getMessage() . "\n\n";
  67. }
  68. } else {
  69. echo "No primary key found for table $table_name.\n";
  70. }
  71. }
  72. echo "\n\nFinished\n";
  73. $conn = null;
Add Comment
Please, Sign In to add comment