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
|
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
// $champs = Champs des tables
// $tables = Table
// $where = Clause WHERE
function requete_sql_update($champs = "", $tables = "", $where = "") {
$connexion = new PDO('mysql:host=localhost;dbname=tests', 'root', 'root', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$connexion->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Champs
$champs_a_afficher = "";
$champs_a_executer = "";
$i = 1;
foreach($champs as $cle => $valeur) {
if ($i == count($champs)) { $virgule = ""; } else { $virgule = ", "; }
$champs_a_afficher .= $cle." = :".$cle.$virgule;
$champs_a_executer .= "':".$cle."' => '".$valeur."'".$virgule;
$i++;
}
try {
$update = $connexion->prepare("UPDATE ".$tables." SET ".$champs_a_afficher." WHERE ".$where."");
$update->execute(array($champs_a_executer));
}
catch (Exception $e) {
$requete_sql = '$update = $connexion->prepare("UPDATE '.$tables.' SET '.$champs_a_afficher.' WHERE '.$where.'");<br />$update->execute(array('.$champs_a_executer.'));';
return '<span style="color:#860E10; font-size:16px">Erreur : '. $e->getMessage().'<br />Requete : '.$requete_sql.'</span>';
}
}
$update = requete_sql_update(
$champs = array('name' => 'Test name', 'price' => 280),
$tables = "products",
$where = "id = 1",
$debug = false
);
echo "<pre>";
echo $update;
echo "</pre>";
// Table products
/*
CREATE TABLE IF NOT EXISTS `products` (
`id` int(2) NOT NULL,
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`price` int(3) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=79 ;
INSERT INTO `products` (`id`, `name`, `price`) VALUES
(1, 'LG Optimus 4X HD P880 Black', 309),
(2, 'Motorola Google Nexus 6, Midnight Blue 32GB', 400),
(3, 'Samsung Galaxy S4 i9500 16GB', 600),
(6, 'Bench Men''s Bench Spokes Slim T-Shirt', 14),
(7, 'HP ZBook 17 Mobile Business Workstation', 514),
(8, 'Samsung Galaxy Tab 4', 210),
(9, 'Spalding Men', 49),
(10, 'Sony Smart Watch 3', 194),
(11, 'Huawei SnapTo', 179),
(12, 'Abercrombie Men''s Lake Arnold Blazer', 25);
ALTER TABLE `products`
ADD PRIMARY KEY (`id`);
ALTER TABLE `products`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=79;
*/
?>
</body>
</html> |
Partager