PHP Flashcards
Define a query for MySQL using PHP?
mysqli_query($connection, $query);
(Query can be an insert, delete etc…
What function can we use for preventing SQL injection attacks on user input?
mysqli_real_escape_string($db, $string);
Old school way…
addslashes($string);
What function do we use to find out what the last connection error was in mysql?
mysqli_connect_error();
mysqli_connect_errno();
What function connects to a database?
mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
What function to you use to determine what error occurred when performing database queries?
mysqli_error($connection);
What function do you use to close a connection with a mysql database?
mysqli_close($connection);
Given a query that returns a number of results, how to you iterate through the results?
$result = mysqli_query($connection, $query);
while ($subject = mysqli_fetch_assoc($result)) { // output the results }
What mysqli api will give you the count of a set?
mysqli_num_rows($set)
This can be useful for determining how many “of a thing” you have
What kind of redirect does header() perform?
302 Redirect
How do you redirect to a page, say “login.php”?
header(“Location: login.php”);
exit;
NOTE: That you don’t need the 302 status code
What does a 302 status in the header do?
It tells the browser to do a second get request to the new location.
Why does session_start have to come at the start of a page?
Because if there isn’t a session, then it will create a cookie - which means modifying the header, and this must happen before ANYTHING is set in the page, much like a header() call.
How would you print the current year in php?
echo date(“Y”);
How would you print the current year in php?
echo date(“Y”);
How would you include a class definition file?
require ‘class.Definition.inc’;
How do you instantiate a class?
$newclass = new Class; $newclass = new Class(); // Both seem to call the constructor
How do you unset a variable that has already been set?
unset($variable_name);
What is a magic method?
An internal callback that is triggered based on an event in a class - i.e. __set is triggered when you attempt to set a variable in a class (if it is inaccessible)
When is __set(string $name, mixed $value) called?
When an inaccessible member is referenced (attempted to write to)
When is __get($name) called?
When an inaccessible value is read from
What is the equivalent of a constructor in PHP?
__construct()
If you have a variable name stored in a variable. How do you access the variable that the name refers to (in a class)?
$this->$name
note the use of $ after the ->
What is the best way to setup a __construct method if you expect to populate it from a database.
Have it populate variables via an array
foreach($data as $name => $value) {
if (in_array($name, array(‘time_created’,
‘time_updated’))) {
$name = ‘_’ . $name;
}
$this->$name = $value;
}
What magic method would you use to allow an object be printed as a string?
__toString()