|
home—lects—exams—hws
D2L—breeze (snow day)
From PHP Visual Quickstart Guide by Larry Ullman.
Originally base on notes by Jack Davis (jcdavis@radford.edu)
This chapter will focus on accessing MySql database tables from PHP programs. A database is a collection of tables (rows & columns) that store information. Databases are created, updated, and read using SQL (Structured Query Language). There are surprisingly few commands in SQL. SQL was designed to be written a lot like the English language, which makes it very user friendly; but it does take some thought to create more elaborate SQL statements with only the handful of available terms.
The process is quite simple: PHP is used to send SQL statements to the database application, where they are executed. The result of the execution - the creation of a table, the insertion of a record, the retrieval of some records, or even an error - is then returned by the database to the PHP script.
$conn = mysql_connect(hostname, username, password); // @param hostname For php.radford.edu, use 'localhost' // @param username your RU userid // @param password the *database* password. |
$connect = mysql_connect(...) || die('connect failed.'); echo "The connection ", ($connect ? "" : "NOT "), "established. |
Common strategy:
Put your '
One kludgy way of doing this is to have the include-file store
the connection it creates in a special variable — perhaps
“
Better,
I suggest having that file define a function named something like
It's also possible to simply have the external file
define a couple variables
(like
$var = 'Amy Johnson'; $qu = "INSERT INTO $tablename (numItems,product,custName) VALUES (17,'abc','$var')"; $allRows = mysql_query($qu); |
$qu = "SELECT * FROM $tablename WHERE (product = 'abc')"; |
while ($oneRow = mysql_fetch_array($allRows)) { # Note use of `=` for assignment *and* return value echo $oneRow['custName'], " bought ", $oneRow['product']; // We could also use $oneRow[0], $oneRow[1], $oneRow[2] but it's preferred to use column-name when possible. } |
$qu = "DELETE FROM $tablename WHERE (field1 = 'abc')"; |
$qu = "UPDATE $tablename SET $field_name1 = 'abc' , $field_name2 = '$newval' WHERE ($field_name1 = '$var')"; $allRows = mysql_query($qu); |
If you want to add or drop FK constraints in mysql: When creating a table, you can specify some Foreign Key (FK) constraints (apparently: from one column to a primary-key column). If you want to have a composite FK involving two columns, or a FK to a non-PK column, you can't just click the myphpAdmin GUI; you'll have to issue the SQL commands. (Note that myphpAdmin includes a pane for typing raw SQL commands, if you don't want to include it in php program.)
-- To create a FK alter table Goo add constraint Goo_ij_FK Foreign key Goo(i,j) references Foo(m,n) -- To delete: alter table Goo drop foreign key Goo_FK -- it seems odd to me, to say 'drop foreign key ...' rather than 'drop constraint ...'. |
If you're having difficulty, you can also see this thread.
$theItem = "coffee"; $theQuery = "SELECT * FROM Inventory WHERE (product = $theItem)"; $results = mysql_query( $theQuery ); |
This is a very common sort of error, and
it can be detected/debugged by printing
A2: If somebody had entered the four-character string “M&Ms” we wouldn't want want to look in our database for something including the characters “amp”. (Our database should include the correct name of the product; we'll turn “M&Ms” into “M&Ms” only when we display that on a web page — but not in emails, internal reports, etc..)
A3: What if the user had entered a name that contains a single-quote? See below, re SQL Injection!
Here is some typical code which validates a user, by looking up their name/password in a table we have previously created:
$user = $_POST['username']; $passwd = $_POST['password']; $qry = "SELECT * FROM MyPasswords WHERE name='$user' and pass='$passwd'"; if (mysql_query($qry)) { // login successful -- we found that name/password in our db! } |
$qry = "SELECT * FROM MyPasswords WHERE name='fred' and pass='xyz123'"; |
BUT:
What if the user had typed in a single-quote in their input?
Suppose they typed e'lan — why will the query fail?
WORSE:
Can the user type in something so that the SELECT statment
always returns a result?
Alas, yes!
Something like:
' or 2+2=4 leads to a query that always turns true.
(Though we still need to deal the final-single-quote that the query is making:)
$qry = "SELECT * FROM MyPasswords WHERE name='fred' and pass='' or 'security' != 'good'"; |
Warning: Always callmysql_real_escape_string on any user-provided string that is getting integrated into a database query.
Now you may feel that if you've already done other validation
on the data and know it doesn't contain any single-quotes or other
characters SQL might mis-interpret,
then you're safe.
That's true.
However, you should still call
(Another reason to call
Securing the data stored in the database.
Suppose we store passwords or credit-cards in our databsae.
What might someday happen (inferring from headlines)?
Sadly, somebody might breach the db itself (aside from the website entirely) —
either a hacker exploiting a DB security hole,
or somebody accidentaly revealing the DB account password,
or an inside employee stealing data.
Solution:
Don't store the password in the database!
“But Barland, how the heck can we verify that they've typed in the
correct password?”
We'll instead store an encrypted form of the password.
Then, when a user later types in the password on a form,
we'll encrypt whatever they type,
and see if the two encryptions are equal.
(Yes, theoretically,
there is tiny (but non-quite-zero!) chance that
two different strings might happen to
encrypt to the same value.
In practice,
I would wait to win the lottery before I worry about two independently-chosen
strings both happen to have hash-values that collide.)
Salt, to help protect against brute-force dictionary attacks.
Rather than
For more details, read the php docs: faq.passwords.php#faq.passwords.fasthash.
home—lects—exams—hws
D2L—breeze (snow day)
©2012, Ian Barland, Radford University Last modified 2012.Nov.07 (Wed) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |