1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
| class PDO3 extends PDO2 {
/* Variables de la classe */
//private $_bidon ="truc" ;
private $_debug = false ;
private $_delimiter = ', '; // ne pas modifier !
private $_type_of_key = array('PRI', 'UNI', 'MUL') ;
protected $_pdo = NULL; // ne doit pas être "private" car héritage de PDO2
/* Constructeur : héritage public obligatoire par héritage de PDO */
public function __construct($pdo)
{
$pdo_ext = $this->checkPdoExtension();
if (isset($pdo) && $pdo_ext) {
$this->_pdo = $pdo;
}
else {
throw new PDOException("No pdo connection");
}
}
/* Destructeur */
public function __destruct() // nota: ne surtout pas mettre de parametre
{
$this->close();
}
/** 28/02/2010
* ferme la connexion à la dB (portage dans la classe PDO de la fonction mysql_close)
*/
public function close()
{
$this->_pdo = NULL;
}
/*
private function methode_bidon ($aff = "methode prive bidon")
{
echo '<br/>'. $aff . ' in this context '.PHP_EOL;
}
*/
/* Methode magique */
public function __toString($object)
{
$string = (string) $object ;
return $string;
}
/* add Field if not exists (Grant Privileges required)*/
public function addField($table_name, $field_name, $field_type, $default_value)
{
// NOTA BENE: la connexion DOIT ETRE OUVERTE avec les privilèges suffisants ...
// ex: `product_selling_net_price` decimal(5,2) NOT NULL
// ALTER TABLE latable ADD / MODIFY / DROP / RENAME lacolonne [nouvelle définition de la colonne]
// NOTA : IF NOT EXISTS can not be used in such a case
// Init
$debug = $this->_debug ;
// Check if not already existing field before adding
$exists = $this->checkFieldExists( $table_name, $field_name );
$aff = ($exists)? "ERR: already existing, can not add as new field <b>$field_name</b> to table <b>$table_name</b>" : "Ok, field <b>$field_name</b> can be added to table <b>$table_name</b>";
if ($debug) echo "<br/>$aff";
// Adding field
if ( false === $exists) {
// Parameters check
// ######
// # ToDo
// ######
// Query
$sql = "ALTER TABLE `$table_name` ADD `$field_name` $field_type $default_value";
$query = $this->_pdo->prepare($sql) ;
$result = $query->execute() ;
}
else {
return false ;
}
if ( $result ) {
if ($debug) echo "<br/>Field $field_name added to table $table_name";
return true;
}
else if ( $result === false ){
if ($debug) {
echo "<br/>Field $field_name <b>NOT added</b> to table $table_name";
return false ; //. mysql_error();
}
else {
return false;
}
}
}
/* Last Id */
public function getLastInsertId()
{
$last_id = $this->_pdo->lastInsertId();
return $last_id;
}
/* Min ($field) */
public function getMin( $table_name, $field , $sql_condition="1")
{
$check_table = $this->checkTableExists($table_name);
if ($check_table) {
$sql = "SELECT min($field) as min_value FROM $table_name WHERE $sql_condition";
$query = $this->_pdo->prepare($sql) ;
$query->execute() ;
$result = $query->fetch(PDO::FETCH_ASSOC);
$min = $result['min_value'];
return $min ;
}
else {
return false ;
}
}
/* Max ($field) */
public function getMax( $table_name, $field, $sql_condition="1" )
{
$check_table = $this->checkTableExists($table_name);
if ($check_table) {
$sql = "SELECT max($field) as max_value FROM $table_name WHERE $sql_condition";
$query = $this->_pdo->prepare($sql) ;
$query->execute() ;
$result = $query->fetch(PDO::FETCH_ASSOC);
$max = $result['max_value'];
return $max ;
}
else {
return false ;
}
}
/** 2/03/2010
* Vérifie l'existence d'une table dans la database grace à une requete préparée
* @param : (string) $db_name, (string) $table_name
* @return : true or false
*/
private function checkTableExists( $table_name)
{
$sql = "SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = '". $this->_dbname . "'
AND TABLE_NAME = '" . $table_name . "'" ;
$query = $this->_pdo->prepare($sql) ;
$result = $query->execute() ;
//if ($this->_debug && false === $result) echo "<br/>PDO3 debug: pas de connection à la table <b>$table_name</b>";
return $result ;
}
/** 9/03/2010
* Vérifie l'existence d'un champ dans la table de la database
* @param : (string) $db_name, (string) $table_name
* @return : true or false
*/
private function checkFieldExists( $table_name, $field_to_check )
{
// Init
$pattern_field = '/^(?:\<b\>)(\w+)(?:\<\/b\>)(?:\s{0,})\((.+)\)(?:\s{0,})\((.+)?\)$/';
$field_name = $field_format = $field_key = array() ;
// db fields
$db_fields = $this->getFieldsName($table_name) ;
if ( empty($db_fields) ) return false ;
foreach ( $db_fields as $field) {
unset($matches);
if ( preg_match($pattern_field, $field, $matches) ) {
$field_name[] = (isset($matches[1]))? trim($matches[1]) : 'name not found' ;
$field_format[] = (isset($matches[2]))? trim($matches[2]) : 'format not found' ;
$field_key[] = (isset($matches[3]))? trim($matches[3]) : 'key not found' ;
}
}
// Matching ?
$matching = (in_array( trim($field_to_check), $field_name )) ? true : false ;
if ( false === $matching && $this->_debug) {
echo "<br/>DEBUG checkFieldExists: not found <b>$field_to_check</b> in <pre>";
print_r($field_name) ;
echo "</pre>";
}
return $matching;
}
/** 2/03/2010
* Retourne la clé primaire d'une table
* @param : (string) $table
* @return : (string) $pk ou false
*/
private function getKey( $table_name, $key_type = 'PRI')
{
if (!in_array( $key_type, $this->_type_of_key ) )
return false ;
$sql = "SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '". $this->_dbname . "'
AND TABLE_NAME = '" . $table_name . "'
AND COLUMN_KEY = '". $key_type. "'
ORDER BY ORDINAL_POSITION" ;
$select = $this->_pdo->prepare($sql) ;
$select->execute() ;
$pk = $select->fetch(PDO::FETCH_ASSOC);
$pk_name = $pk['COLUMN_NAME'];
//if ($this->_debug) echo '<br/>getKey: ' . $pk_name ;
return $pk_name ;
}
/** 2/03/2010
* Retourne la clé primaire d'une table ainsi que sa valeur pour une ligne donnée en fonction d'une condition de recherche
* @param : (string) $table, (string) $sql_condition
* @return : (array) $pk ou false
*/
public function getRecordID($table_name, $sql_condition)
{
// Verif initiales
// Table existante
$check_table = $this->checkTableExists($table_name);
//if (false === $check_table && $this->_debug) echo '<br/>DEBUG getRecordId err 1';
if (false === $check_table) return false ;
// PK existe
$pk_name = $this->getKey( $table_name, 'PRI') ;
//if (false === $pk_name && $this->_debug) echo '<br/>DEBUG getRecordId err 2';
if (false === $pk_name) return false ;
// Condition de recherche valide
list($condition_field_name, $condition_field_value) = explode("=", $sql_condition);
//if ( empty($condition_field_name) || empty($condition_field_name) && $this->_debug) echo '<br/>DEBUG getRecordId err 3';
if ( empty($condition_field_name) || empty($condition_field_name) ) return false ;
// Verif de l'existence du champ de recherche
// #######
// # to do
// #######
// Requetes SQL et execution
$sql = "SELECT $pk_name FROM $table_name WHERE $sql_condition LIMIT 1" ;
$select = $this->_pdo->prepare($sql) ;
$select->execute() ;
$id = $select->fetch(PDO::FETCH_ASSOC);
/*
if ($this->_debug) {
echo '<br/>DEBUG GetRecordId ';
echo '<br/>$sql = ' . $sql;
echo '<br/>id found = <pre>'; print_r($id); echo '</pre>' ;
}
*/
$id = $id[$pk_name];
if ( empty($id) || !isset($id) ) {
return false;
}
else {
return $id;
}
}
/**
* Retourne la liste résumée des tables de la base
* @doc : http://cedric-duprez.developpez.com/tutoriels/mysql/catalogue/#LV
* @return : (array) $data_array
*/
public function getFieldsSummary($limit = false)
{
$data_array = array();
$limit = ($limit == false)? '' : 'LIMIT '. (int) $limit;
// Les tables, dans l'ordre = f(taille)
$sql = "SELECT TABLE_NAME, ROUND((DATA_LENGTH + INDEX_LENGTH) / (1024 * 1024), 2) AS SIZE_MO, TABLE_ROWS, AUTO_INCREMENT
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = '". $this->_dbname . "'
ORDER BY DATA_LENGTH + INDEX_LENGTH DESC ". $limit;
$result = $this->_pdo->query($sql);
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $key => $value) {
$data_array[$key] = $value;
}
return $data_array;
}
/**
* Retourne la liste détaillée des tables de la base
* @doc : http://cedric-duprez.developpez.com/tutoriels/mysql/catalogue/#LV
* @return : (array) $data_array
*/
public function getFieldsDetails($limit = false)
{
$data_array = array();
$limit = ($limit == false)? false : (int) $limit;
// Summary: reprise de ces infos comme base de recherche des détails
$source_array = $this->getFieldsSummary($limit);
// Details
foreach( $source_array as $key => $field_datas) {
if (is_array($field_datas)) {
// Transfert du Summary dans le tableau de détails
$data_array[$key] = $field_datas;
// Details de chaque table
$table_encours = $field_datas['TABLE_NAME'];
$sql = "SELECT COLUMN_NAME, COLUMN_TYPE, COLUMN_KEY, EXTRA
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '". $this->_dbname . "'
AND TABLE_NAME = '" . $table_encours . "'";
$result = $this->_pdo->query($sql);
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
// Field List
$field_list= '';
$memo_auto_inc = '' ;
$count = count($rows);
foreach($rows as $k => $value) {
$memo_auto_inc = ($value['EXTRA'] == 'auto_increment')? $value['COLUMN_NAME'] : $memo_auto_inc ;
$field_list .= '<b>'. $value['COLUMN_NAME'] . '</b> (' . $value['COLUMN_TYPE'] . ') ' . ' (' . $value['COLUMN_KEY'] . ')'. $this->_delimiter;
}
// Marqueur éventuel sur l'AI
$data_array[$key]['AI_RESET_NEED'] = ($data_array[$key]['AUTO_INCREMENT'] > $count) ? 'true' : 'false' ;
$data_array[$key]['AI_FIELD'] = $memo_auto_inc ;
// Array Push
$data_array[$key]['FIELDS_COUNT'] = $count;
$data_array[$key]['FIELDS_LIST'] = $field_list;
}
}
return $data_array;
}
/** 28/02/2010 portage dans la classe PDO de la fonction db_pdo.php
* retourne la liste des champs d'une table sous forme de vecteur colonne
* @param : (string) $table_name nom de la table dont on veut la liste des champs
* @return : (array) $fieldNames liste des noms de champs de $table_name
*/
public function getFieldsName($table_name)
{
// Field Details: reprise de ces infos comme base de recherche des détails
$source_array = $this->getFieldsDetails(false);
// 1ere méthode: lourde et peu élégante
/*
$fieldNames = array() ;
foreach ($source_array as $key => $table_datas) {
if (is_array($table_datas)) {
if ($table_datas['TABLE_NAME'] == $table_name) {
$fieldNames = explode( $this->_delimiter , $table_datas['FIELDS_LIST'] ) ;
}
}
}
array_pop($fieldNames) ;
*/
// 2eme méthode: plus directe et élégante : recupération récursive de la clé correspondante à la table
$key = $this->recursiveArraySearch($table_name , $source_array ) ;
$fieldNames = explode( $this->_delimiter , $source_array[$key]['FIELDS_LIST'] ) ;
array_pop($fieldNames);
// 3eme methode: brut accès direct aux infos dB sans utiliser d'autres fonctions
/*
$recordset = $this->_pdo->query("SHOW COLUMNS FROM $table_name");
$fields = $recordset->fetchAll(PDO::FETCH_ASSOC);
foreach ($fields as $field) {
$fieldNames[] = $field['Field'];
}
*/
return $fieldNames;
}
/**
* Affecte une valeur dans toute une colonne selon une condition optionnelle
* @return : $count nbre d'enregistrement affectés ou false
*/
public function updateColumn($table_name, $field_name, $data_cste, $sql_condition=false )
{
// ex: UPDATE product_supply_base SET `product_selling_net_price` = 300 WHERE `product_ref`=10009
// Verif existante Table
$table_ok = $this->checkTableExists( $table_name) ;
if ($this->_debug && false === $table_ok) echo '<br/>DEBUG update Column: table Nok';
if ( false === $table_ok ) return false ;
// Verif existante Fields
$destination_Ok = $this->checkFieldExists( $table_name, $field_name ) ;
if ($this->_debug && false === $destination_Ok ) echo '<br/>DEBUG update Column: fields Nok';
if ( false === $destination_Ok ) return false ;
// Verif data_cste
if ($this->_debug && empty($data_cste) ) echo '<br/>DEBUG update Column: champ source et destination identiques: <b>Nok</b>';
if ( empty($data_cste) ) return false ;
// Verif sql condition et champ obligatoire
list($condition_field_name, $condition_field_value) = explode("=", $sql_condition);
$test = (empty($condition_field_name) || empty($condition_field_name) || false === $this->checkFieldExists( $table_name, $condition_field_name ) );
if ($this->_debug && $test ) echo '<br/>DEBUG update Column: sql condition Nok';
if ( $test ) return false ;
// Verif compatibilté du format $data_cste avec le format de la colonne
// ######
// # ToDo
// ######
// Update Column with constante value under sql_condition
$sql = "UPDATE $table_name SET $field_name = $data_cste WHERE $sql_condition" ;
$query = $this->_pdo->prepare($sql) ;
$result = $query->execute() ;
$count = $query->rowCount();
if ($result) {
return $count;
}
else {
if ($this->_debug && false === $result) echo '<br/>DEBUG update Column: result Nok';
return false ;
}
}
/** 28/02/2010 portage dans la classe PDO de la fonction incluse dans db_pdo.php
* sauve des datas (variables ou array) INSERT ou UPDATE dans la table $table de la dB
* @NOTA : fonction dépréciée au profit de la fonction saveData sauf si l'on veut ajouter une condition sur une table sans pk
* @param : $table_name, $data_array
* @return : true si tout s'est bien passé, false sinon
* @doc : http://fr.php.net/manual/fr/function.mysql-query.php#84962
*/
public function addData($table_name, $excluded_fields = '', $data_array, $sql_type = 'insert', $sql_condition = NULL )
{
// Init
$fields = '';
$values = '';
$debug = $this->_debug ;
$pattern = '/tel|phone|fax|siret|number|numero/';
// format input fields into sql (explode du tableau associatif en requete SQL)
foreach ($data_array as $field => $value) {
if (!strstr($excluded_fields, $field)) {
// construction de la sql pour INSERT
if (strtolower($sql_type) == 'insert') {
$fields .= "$field, ";
$values .= "'$value', ";
}
// construction de la sql pour UPDATE
else {
if (!is_numeric($value)) {
$fields .= "$field = '$value', "; // string
}
else {
// exceptions: pour le num de tel/fax/siret qui peut commencer par un zero et peut ainsi être assimilé à un numeric, ce qui n'est pas le cas ds la dB
if ( !preg_match( $pattern, $field ) ) {
$fields .= "$field = $value, "; // numeric
}
else {
$fields .= "$field = '$value', ";// si tel/phone/fax/siret etc.. => string
}
}
}
}
}
// remove trailing ", " from $fields and $values
$fields = preg_replace('/, $/', '', $fields);
$values = preg_replace('/, $/', '', $values);
// create sql statement
if (strtolower($sql_type) == 'insert') {
$sql = "INSERT INTO $table_name ($fields) VALUES ($values)";
}
elseif (strtolower($sql_type) == 'update') {
if (!isset($sql_condition)) {
if ($debug) echo 'ERROR: You must enter a sql condition!';
exit;
}
$sql = "UPDATE $table_name SET $fields WHERE $sql_condition";
}
else {
if ($debug) echo 'ERROR: Invalid input for argument $sql_type: must be "insert" or "update"';
exit;
}
// prepare & execute sql
$query = $this->_pdo->prepare($sql) ;
$result = $query->execute() ;
//$result->closeCursor(); // not always necessary: depends on SQL driver needs
if ( $result ) {
return true;
}
else if ( $result === false ){
if ($debug) {
return 'err sql: ' ; //. mysql_error();
}
else {
return false;
}
}
} // fin addData
/** 01/03/2010
* sauve $data_array dans $table (la condition d'UPDATE devenant optionnelle si cette condition ne porte que sur l'id PK)
* @param : $table_name destination, $data_array à sauver, $sql_type='insert' ou 'update', $optional_condition
* @doc : http://www.php.net/manual/fr/pdostatement.execute.php#80499
* @return : true si tout s'est bien passé, false sinon
*/
public function saveData($table_name, $data_array, $sql_type='insert', $optional_condition=NULL )
{
// Init
$debug = $this->_debug;
$sql ='';
$pattern_field = '/^(?:\<b\>)(\w+)(?:\<\/b\>)(?:\s{0,})\((.+)\)(?:\s{0,})\((.+)?\)$/';
$field_name = $field_format = $field_key = array() ;
// Initial checks
// Data_array in line with table fields
// db fields
$db_fields = $this->getFieldsName($table_name) ;
if ( empty($db_fields) ) return false ;
foreach ( $db_fields as $field) {
unset($matches);
if ( preg_match($pattern_field, $field, $matches) ) {
$field_name[] = (isset($matches[1]))? trim($matches[1]) : 'name not found' ;
$field_format[] = (isset($matches[2]))? trim($matches[2]) : 'format not found' ;
$field_key[] = (isset($matches[3]))? trim($matches[3]) : 'key not found' ;
}
}
if ($debug) {
$this->arr_dump(array('keys'=>$field_key, 'names'=>$field_name, 'formats'=>$field_format) , 'Matching results');
}
// Comparison $db_fields with $data_array: can accept missing fields but no mismatching fields (thus avoiding typos in $data_array)
$mismatching_fields = array_diff(array_keys($data_array), $field_name);
if ( count($mismatching_fields) != 0) {
if ($debug) {
echo '<br/>PDO3 db Vs data fields issue';
$this->arr_dump($mismatching_fields, 'mismatch' );
}
return false;
}
// Check data_array format Vs dB_fields format
// #########
// # To do
// #########
// Build SQL statement
// INSERT $sql = "INSERT INTO $table_name ($fields) VALUES ($values)";
$fields = '';
$values = '';
if ( strtolower($sql_type) == 'insert') {
foreach($data_array as $field => $data) {
$fields .= "$field, ";
$values .= "'$data', ";
}
$fields = preg_replace('/, $/', '', $fields);
$values = preg_replace('/, $/', '', $values);
$sql = "INSERT INTO $table_name ($fields) VALUES ($values)";
if ($debug) echo '<br/>sql statement: ' . $sql;
}
// UPDATE
if ( strtolower($sql_type) == 'update') {
if ($debug) echo '<br/>Starting update....' ;
// Update Condition $sql_condition
$sql_condition = '';
// dB primary key field required
$needle = 'PRI';
$pk_key = trim($this->recursiveArraySearch($needle, $field_key) ) ;
if (false === $pk_key ) { // NOTA: '===' is a must as $pk_key can be 0 and then understood as 'false'
if ($debug) {
echo '<br/>PDO3 Err: no primary key found' ;
$this->arr_dump( array('pk key'=> $pk_key , 'needle'=>$needle, 'fields' => $field_key), 'Check needle & arrays') ;
}
return false;
}
else {
if ($debug) {
echo '<br/>found primary key in db datas array <b>keys</b> :' . $pk_key;
$this->arr_dump( $field_key , 'field_key');
}
}
// data_array primary key check
$pk_value = (array_key_exists($field_name[$pk_key], $data_array))? $data_array[$field_name[$pk_key]] : false ;
if (false === $pk_value || empty($pk_value) ) {
if ($debug) $this->arr_dump( array('key'=>$pk_key, 'value'=>$pk_value, 'data'=>$data_array) , 'PDO3 Err: no data content for primary key sql condition');
return false ;
}
else if ($debug) echo '<br/>found primary key value in db datas array <b>values</b>:' . $pk_value;
// db_field: check if table field of row(pk) exists (in order to being able to properly set the sql_condition)
// #########
// # to do
// #########
// Sql condition (base)
$sql_condition = $field_name[$pk_key] . '=' . $pk_value;
if ($debug) echo '<br/>sql update condition base: ' . $sql_condition ;
// Sql condition (options)
// #########
// # to do: check if necessary (prepared request) that the optional sql condition is not matching with forbidden conditions like 1=1 or DELETE..
// #########
// Sql condition (global)
$sql_condition .= ($optional_condition)? ' AND ' . $optional_condition : '' ;
// Build sql statement (not necessary to remove PK field from fields to alter)
$fields = '';
foreach($data_array as $field => $data) {
$fields .= "$field = '$data', ";
}
// remove trailing ','
$fields = preg_replace('/, $/', '', $fields);
// Sql final statement
$sql = "UPDATE $table_name SET $fields WHERE $sql_condition";
if ($debug) echo '<br/>sql statement: ' . $sql;
}
// Prepare & Execute Sql statement (sothat there is no need to use "quote" method for data protection against SQL injection)
if ($sql) {
$query = $this->_pdo->prepare($sql) ;
$result = $query->execute() ;
$count = $query->rowCount(); // Check affected rows by INSERT or UPDATE (nota : this methode does not work for SELECT)
if (strtolower($sql_type) == 'insert') {
$affected_rows = ($count > 0) ? true : false ;
}
else {
$affected_rows = ($count >= 0) ? true : false ;
}
}
// Return Value
if ($result && $affected_rows) {
return true;
}
else{
return false;
}
} /* fin saveData */
/**
* Backup d'un champ dans un champ destination (alors écrasé)
* @return : $count nbre d'enregistrement affectés ou false
*/
public function copyPaste($table_name, $field_source, $field_destination, $sql_condition="1=1") {
// ex: UPDATE product_supply_base SET `previous_selling_price` = product_selling_net_price WHERE `product_ref` = 10009
// Verif existante Table
$table_ok = $this->checkTableExists( $table_name) ;
if ($this->_debug && false === $table_ok) echo '<br/>DEBUG Copy/Paste: table Nok';
if ( false === $table_ok ) return false ;
// Verif existante Fields
$source_Ok = $this->checkFieldExists( $table_name, $field_source ) ;
$destination_Ok = $this->checkFieldExists( $table_name, $field_destination ) ;
if ($this->_debug && (false === $destination_Ok || false === $source_Ok) ) echo '<br/>DEBUG Copy/Paste: fields Nok';
if ( false === $destination_Ok || false === $source_Ok ) return false ;
// Verif que Destination différente de la Source
$egalite = ($field_source == $field_destination) ;
if ($this->_debug && $egalite) echo '<br/>DEBUG Copy/Paste: champ source et destination identiques: <b>Nok</b>';
if ($egalite) return false ;
// Verif sql condition
list($condition_field_name, $condition_field_value) = explode("=", $sql_condition);
$test = (empty($condition_field_name) || empty($condition_field_name) || false === $this->checkFieldExists( $table_name, $condition_field_name ) );
if ($this->_debug && $test ) echo '<br/>DEBUG Copy/Paste: sql condition Nok';
if ( $test ) return false ;
// Update Copy /Paste
$sql = "UPDATE $table_name SET $field_destination = $field_source WHERE $sql_condition" ;
$query = $this->_pdo->prepare($sql) ;
$result = $query->execute() ;
$count = $query->rowCount();
if ($result) {
return $count;
}
else {
if ($this->_debug && false === $result) echo '<br/>DEBUG Copy/Paste: result Nok';
return false ;
}
}
/**
* Comptage du nbre enregistrements (par requete préparée)
* @return : $count
*/
public function countId($table_name, $id_name, $id_value) {
// méthode alternative : voir http://php.developpez.com/faq/?page=pdo#pdo-count
// #####
// NOTA: à modifier pour ne selectionner que les enregistrements de la PK (utiliser fonction existante)
// #####
$sql_prep = "SELECT COUNT(*) FROM $table_name WHERE $id_name= :id_value" ;
$query = $this->_pdo->prepare($sql_prep) ;
$query->execute(array( ':id_value' => $id_value ));
$count = $query->fetchColumn();
$query->closeCursor();
return $count;
}
/**
* Comptage du nbre enregistrements DISTINCTS pour un champ donné avec condition (par requete préparée)
* @return : $count
*/
private function countDistinct($table_name, $field, $sql_condition=false) {
// Verif sql condition
list($condition_field_name, $condition_field_value) = explode("=", $sql_condition);
if ( empty($condition_field_name) || empty($condition_field_name) || false === $this->checkFieldExists( $table_name, $condition_field_name )) return false ;
// Query
$sql_prep = "SELECT DISTINCT $field FROM $table_name WHERE $sql_condition" ;
$query = $this->_pdo->prepare($sql_prep) ;
$query->execute();
$count = count($query->fetchAll());
$query->closeCursor();
return $count;
}
/**
* Comptage du nbre enregistrements DISTINCTS pour un champ donné avec condition (par requete préparée)
* @return : $count
*/
public function isUnique($table_name, $field, $sql_condition) {
// méthode alternative : voir http://php.developpez.com/faq/?page=pdo#pdo-count
$count = $this->countDistinct($table_name, $field, $sql_condition) ;
$unique = ($count == 1) ? true : false ;
return $unique;
}
/**
* Recherche récursive de la clé de niveau 0 d'une valeur située dans un tableau multidimensionnel de profondeur D
* @source : http://fr.php.net/manual/fr/function.array-search.php#91365
* @return : $key($needle)
*/
private function recursiveArraySearch($needle, $haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && $this->recursiveArraySearch($needle, $value) !== false)) {
return $current_key;
}
}
return false;
}
/** 01/02/2010
* Vérifie que l'extension pdo est bien chargée et est bien en phase avec le type des requetes émises dans la classe PDO2
* @source : http://php.developpez.com/faq/?page=pdo#pdo-loaded-drivers
* @return : true ou false
*/
// ######### à ré-implémenter en amont dans PDO2 avec gestion erreur ################
private function checkPdoExtension() {
if ($this->_debug) echo '<br/>Checking for PDO extension loaded';
$pdo_ext = false;
foreach(get_loaded_extensions() as $extension) {
if(strpos(strtolower($extension), 'pdo') !== 'pdo') {
$pdo_ext = true;
}
}
if ($this->_debug && false == $pdo_ext) echo '<br/>PDO extension not loaded';
return $pdo_ext;
}
/**
* fonction de debugage
*/
private function arr_dump($array, $text='') {
echo '<br/>Dump('.$text.')<pre>'; print_r($array); echo '</pre>' ;
}
} /* fin de la Classe */
?> |
Partager