Created
March 17, 2016 20:09
-
-
Save hanleybrand/0d3132ce3a209b510c97 to your computer and use it in GitHub Desktop.
php db code from learnyouphp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| $old_name = $argv[2]; | |
| $new_name = 'David Attenborough'; | |
| $pdo = new \PDO($argv[1]); | |
| foreach ($pdo->query('SELECT * FROM users') as $row) { | |
| if ($row['age'] > 30 ) { | |
| echo "User: " . $row['name'] . " Age: " . $row['age'] . " Sex: " . $row['gender'] . "\n"; | |
| } | |
| } | |
| $repl = $pdo->prepare('UPDATE users SET name=:new_name WHERE name = :old_name'); | |
| $repl->bindParam(':new_name', $new_name); | |
| $repl->bindParam(':old_name', $old_name); | |
| $repl->execute(); | |
| // official solution | |
| //$db = new \PDO($argv[1]); | |
| //$users = $db->query('SELECT * FROM users WHERE age > 30'); | |
| //foreach ($users as $user) { | |
| // echo "User: {$user['name']} Age: {$user['age']} Sex: {$user['gender']}\n"; | |
| //} | |
| //$nameToUpdate = $argv[2]; | |
| //$stmt = $db->prepare('UPDATE users SET name = :newName WHERE name = :oldName'); | |
| //$stmt->execute([':newName' => 'David Attenborough', ':oldName' => $nameToUpdate]); | |
| //good praxis http://www.phptherightway.com/#pdo_extension | |
| //$pdo = new PDO('sqlite://users.db'); | |
| //$stmt = $pdo->prepare('SELECT name FROM users WHERE id = :id'); | |
| //$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT); // <-- filter your data first | |
| // // (see [Data Filtering](#data_filtering)), | |
| // // especially important for INSERT, UPDATE, etc. | |
| // | |
| //$stmt->bindParam(':id', $id, PDO::PARAM_INT); // <-- Automatically sanitized for SQL by PDO | |
| //$stmt->execute(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment