PHP 101 (part 8): Databases and Other Animals – Part 1
Mix and Match
Building Blocks
Animal Magnetism
Hello Database!
Different Strokes…
…for Different Folks
PHP 101 (part 8): Databases and Other Animals – Part 2
Mix and Match
One of the most compelling things PHP has going for it is its
support for a variety of database management systems, including MySQL,
PostgreSQL, Oracle and Microsoft Access. By virtue of this support, PHP
developers can create sophisticated data-driven Web applications at a
fraction of the time and cost required by competing alternatives. And
nowhere is this more clear than in PHP’s longtime support of MySQL, the
very fast, very reliable and very feature-rich open-source RDBMS.
By using PHP and MySQL together, developers can benefit from huge
savings on the licensing costs of commercial alternatives, and also
leverage off the tremendous amount of thought PHP and MySQL developers
have put into making sure that the two packages work together
seamlessly and smoothly. And since both PHP and MySQL are open-source
projects, when you use the two of them together you know
you’re getting the most up-to-date technology available. And that’s
always a good thought to go to bed with.
OK. Enough of the marketing talk. Let’s get down to business.
In this issue of PHP 101, I’m going to show you how to use PHP to
extract data from a database, and use that data to dynamically build a
Web page. In order to try out the examples in this tutorial, you’ll
need a working MySQL installation, which you can obtain from the MySQL
Web site at http://www.mysql.com/.
If you have some knowledge of SQL
(Structured Query Language, the language used to interact with a
database server) you’ll find it helpful, but it’s not essential.
Building Blocks
In order to use MySQL and PHP together, your PHP build must include
support for MySQL. On UNIX, this is accomplished by adding the
--with-mysql option to the configure script
when building PHP on UNIX, and pointing PHP to the MySQL client
libraries. On Windows, the MySQL client libraries are built in to
PHP 4 and activated by default. In PHP 5, pre-built .dll files
are included with the Windows distribution. Read more about this at
http://www.php.net/manual/en/ref.mysql.php.
Unix users should note that PHP 4 ships with a set of MySQL
client libraries, which are activated by default; however, PHP
5 no longer bundles these libraries due to licensing issues, so you
need to obtain, install and activate them yourself. They’re included
with the MySQL distribution, and are installed automatically when you
install MySQL. To activate the MySQL extension, ext/mysql,
add the --with-mysql option to PHP’s configure
script. For more information on this change, read
http://www.php.net/manual/en/faq.databases.php#faq.databases.mysql.php5.
And finally (as if all that wasn’t quite confusing enough) PHP 5 also
comes with a new MySQL extension, called ext/mysqli
(MySQL Improved). You can use this new extension to access the new
features in MySQL 4.1.2 or better, and to gain the benefits of improved
speed and security. To activate this extension on UNIX, add the
--with-mysqli option to PHP’s configure script,
and point PHP to the mysql_config program that comes with
MySQL 4.1 and above. For Windows users, a pre-built version of
ext/mysqli is included in the win32 PHP distribution. Read
more about this at http://www.php.net/manual/en/ref.mysqli.php.
To figure out which extension you need, use the following rule of thumb:
- If you need the new features in MySQL 4.1.2 or better, or if you’re
using an older version of MySQL but still want to benefit from the
speed/security improvements in the new extension, useext/mysqli. - If you don’t fall into either of the categories above, or don’t know what I’m
talking about, use regularext/mysql.
In case you were wondering, this tutorial covers both ext/mysql
and ext/mysqli, so you actually get two for the price of
one. Keep reading, and let me introduce you to MySQL.
Animal Magnetism
Every MySQL database is composed of one or more tables. These
tables, which structure data into rows and columns, are what lend
organization to the data.
Here’s an example of what a typical table looks like:
+----+-----------+----------+ | id | country | animal | +----+-----------+----------+ | 1 | America | eagle | | 2 | China | dragon | | 3 | England | lion | | 4 | India | tiger | | 5 | Australia | kangaroo | | 6 | Norway | elk | +----+-----------+----------+
As you can see, a table divides data into rows, with a new entry (or
record) on every row. The data in each row is further broken
down into cells (or fields), each of which contains a value for
a particular attribute of the data. For example, if you consider the
record for the country “India”, you’ll see that the record is clearly
divided into separate fields for record number, country name and
national animal.
The rows within a table are not arranged in any particular order -
they can be sorted alphabetically, by number, by name, or by any
other criteria you choose to specify. It is therefore necessary to have
some method of identifying a specific record in a table. In the example
above, each record is identified by a unique number; this unique field
is referred to as the primary key for that table.
You use the Structured Query Language, SQL, to interact with the MySQL
server and tell it to create a table, mark a field as primary, insert
records, edit records, retrieve records… basically, anything that
involves manipulating the data or the database. To see how this works,
examine the following SQL, which creates the table above:
CREATE DATABASE testdb;
CREATE TABLE `symbols` (
`id` int(11) NOT NULL auto_increment,
`country` varchar(255) NOT NULL default '',
`animal` varchar(255) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM;
INSERT INTO `symbols` VALUES (1, 'America', 'eagle');
INSERT INTO `symbols` VALUES (2, 'China', 'dragon');
INSERT INTO `symbols` VALUES (3, 'England', 'lion');
INSERT INTO `symbols` VALUES (4, 'India', 'tiger');
INSERT INTO `symbols` VALUES (5, 'Australia', 'kangaroo');
INSERT INTO `symbols` VALUES (6, 'Norway', 'elk');
You can enter these commands either interactively or
non-interactively through the MySQL commandline client program,
which you run by navigating to the mysql/bin
directory from your shell or DOS box and typing – with no
; because this is a shell command – either
mysql, or mysql db_name if you want
to choose an existing database to work with. Read
http://dev.mysql.com/doc/mysql/en/mysql.html for more information
on how to use the MySQL commandline client, and the tutorial at
http://www.melonfire.com/community/columns/trog/article.php?id=39
to understand what each of the SQL commands above does. SQL is a
lot like spoken English, so it won’t take you very long to pick it
up. Just don’t try to turn those backticks into single quotation marks.
Once the data has been imported, run a quick SELECT
query to check that everything is working as it should be:
mysql> SELECT * FROM `symbols`; +----+-----------+----------+ | id | country | animal | +----+-----------+----------+ | 1 | America | eagle | | 2 | China | dragon | | 3 | England | lion | | 4 | India | tiger | | 5 | Australia | kangaroo | | 6 | Norway | elk | +----+-----------+----------+ 6 rows in set (0.06 sec)
In English, the query above means “show me all the records from the
table named symbols“. If you saw the same output as above,
you’re good to go!
Hello Database!
Now, let’s use PHP to do exactly the same thing. You could use PHP
to set up the database from the start, but as ours already exists
we’ll simply fire a SELECT query at the database
‘testdb’, and display the results in an HTML page:
<html>
<head>
<basefont face="Arial">
</head>
<body>
<?php
// set database server access variables:
$host = "localhost";
$user = "test";
$pass = "test";
$db = "testdb";
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
// create query
$query = "SELECT * FROM symbols";
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// print them one after another
echo "<table cellpadding=10 border=1>";
while($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>".$row[0]."</td>";
echo "<td>" . $row[1]."</td>";
echo "<td>".$row[2]."</td>";
echo "</tr>";
}
echo "</table>";
}
else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
mysql_free_result($result);
// close connection
mysql_close($connection);
?>
</body>
</html>
Here’s what the result looks like:
As you can see, using PHP to get data from a database involves
several steps, each of which is actually a pre-defined PHP function.
Let’s dissect each step:
- The first thing to do is specify some important information needed
to establish a connection to the database server. This information
includes the server name, the username and password required to gain
access to it, and the name of the database to query. These values are
all set up in regular PHP variables.
<?php$host = "localhost";
$user = "test";
$pass = "test";
$db = "testdb";?>
- To begin communication with a MySQL database server, you need to
open a connection to that server. All communication between PHP and
the database server takes place through this connection.In order to initialize this connection, PHP offers the
mysql_connect()function:
<?php$connection = mysql_connect($server, $user, $pass);
?>
All the parameters in
mysql_connect()are optional, but there
are three you will generally need to use anywhere beyond your own machine:
the database server name, username and password. If the database server
and the Web server are running on the same physical machine, you can use
localhostas the database server name this is in fact the
default value supplied by PHP.mysql_connect()returns a “link identifier”, which is stored
in the variable$connection. This identifier is used when
communicating with the database. - Once you have a connection to the database, you must select
a database for use with themysql_select_db()function:
<?phpmysql_select_db($db) or die ("Unable to select database!");
?>
This function must be passed the name of the database to be used for
all subsequent queries. An optional second argument here is the link
identifier; if no identifier is specified, the last opened link is
assumed. If you have two or more database connections open
simultaneously, it’s a good idea to specify the link identifier as the
second argument tomysql_select_db()– and indeed to all other
mysql_* functions in the script, so that PHP doesn’t get confused about
which connection to use where. - The next step is to create the query and execute it. This
is accomplished with themysql_query()function.
<?php$query = "SELECT * FROM symbols";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
?>
This function also needs two parameters: the query string and the
link identifier for the connection. Again, if no link identifier is
specified, the last opened link is used. Depending on whether or not
the query was successful, the function returns true or false; a failure
can be caught via the...or die()clause of the statement,
and themysql_error()function can be used to display the
corresponding error message. - If
mysql_query()is successful, the result set returned
by the query is stored in the variable$result. This result set may
contain one or more rows or columns of data, depending on your query. You can
retrieve specific subsets of the result set with different PHP functions,
including the one used here – themysql_fetch_row()function -
which fetches a single row of data as an array called$row. Fields
in that row can then be accessed using standard PHP array notation.Each time you call
mysql_fetch_row(), the next record in the result
set is returned. This makesmysql_fetch_row()very suitable for
use in awhile()orfor()loop.
<?phpif (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)) {
echo "<td>".$row[0]."</td>";echo "<td>".$row[1]."</td>";
echo "<td>".$row[2]."</td>";}
}?>
Notice that the call to
mysql_fetch_row()is wrapped in a
conditional test, which first checks to see if any rows were returned
at all. This information is provided by themysql_num_rows()
function, which contains the number of rows returned by the query. Obviously,
you can only use this function with queries that return data, like
SELECTorSHOW.It is not appropriate for use withINSERT,UPDATE,DELETEor similar queries.There are several other alternatives to
mysql_fetch_row(),
which will be explained a little later. - Finally, since each result set returned after a query
occupies memory, it’s a good idea to use themysql_free_result()
function to free up the used memory. After the result set is freed, if no
further queries are to be run, you can close the connection to the MySQL
server withmysql_close().
<?phpmysql_free_result($result);
mysql_close($connection);?>
Different Strokes…
You can also use PHP’s mysql_fetch_row() and list()
functions to obtain a simple array of values, and then assign these values to
different variables – a variation of the technique in the previous section.
Take a look (only the while() loop changes):
<html>
<head>
<basefont face="Arial">
</head>
<body>
<?php
// set server access variables
$host = "localhost";
$user = "test";
$pass = "test";
$db = "testdb";
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
// create query
$query = "SELECT * FROM symbols";
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// print them one after another
echo "<table cellpadding=10 border=1>";
while(list($id, $country, $animal) = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>$id</td>";
echo "<td>$country</td>";
echo "<td>$animal</td>";
echo "</tr>";
}
echo "</table>";
}
else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
mysql_free_result($result);
// close connection
mysql_close($connection);
?>
</body>
</html>
In this case, the list() function is used to assign different
elements of the result set to PHP variables, which are then used when
rendering the page.
You can use PHP’s mysql_fetch_assoc() function to represent each
row as an associative array of field-value pairs – a minor variation of the
technique used above:
<html>
<head>
<basefont face="Arial">
</head>
<body>
<?php
// set server access variables
$host = "localhost";
$user = "test";
$pass = "test";
$db = "testdb";
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
// create query
$query = "SELECT * FROM symbols";
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// print them one after another
echo "<table cellpadding=10 border=1>";
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['country']."</td>";
echo "<td>".$row['animal']."</td>";
echo "</tr>";
}
echo "</table>";
}
else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
mysql_free_result($result);
// close connection
mysql_close($connection);
?>
</body>
</html>
Notice that in this case, field values are accessed using the field
name instead of the index.
Of all the alternatives, however, the function I like the most is
the mysql_fetch_object() function, which returns each
row as an object (remember them from Part Seven?) with properties
corresponding to the field names:
<html>
<head>
<basefont face="Arial">
</head>
<body>
<?php
// set server access variables
$host = "localhost";
$user = "test";
$pass = "test";
$db = "testdb";
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
// create query
$query = "SELECT * FROM symbols";
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// print them one after another
echo "<table cellpadding=10 border=1>";
while($row = mysql_fetch_object($result)) {
echo "<tr>";
echo "<td>".$row->id."</td>";
echo "<td>".$row->country."</td>";
echo "<td>".$row->animal."</td>";
echo "</tr>";
}
echo "</table>";
}
else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
mysql_free_result($result);
// close connection
mysql_close($connection);
?>
</body>
</html>
Here, each $row object is created with properties
corresponding to the field names in that row. Row values can
thus be accessed using standard object->property
notation.
If you’re the type that likes to have your cake and eat it too, you
will probably enjoy the mysql_fetch_array() function, which
returns both an associative array and a numerically-indexed array, a
combination of the mysql_fetch_row() and
mysql_fetch_assoc() functions. Read about it at
http://www.php.net/manual/en/function.mysql-fetch-array.php.
…for Different Folks
If you’re using PHP 5, you can do the same thing using the new
ext/mysqli extension, which offers a number of new features. This
extension can be used in two ways: procedural (using functions), and
object-oriented (using class methods and properties). Consider the next
script, which uses ext/mysqli in a procedural manner:
<html>
<head>
<basefont face="Arial">
</head>
<body>
<?php
// set server access variables
$host = "localhost";
$user = "test";
$pass = "test";
$db = "testdb";
// open connection
$connection = mysqli_connect($host, $user, $pass, $db) or die ("Unable to connect!");
// create query
$query = "SELECT * FROM symbols";
// execute query
$result = mysqli_query($connection, $query) or die ("Error in query: $query. ".mysqli_error());
// see if any rows were returned
if (mysqli_num_rows($result) > 0) {
// yes
// print them one after another
echo "<table cellpadding=10 border=1>";
while($row = mysqli_fetch_row($result)) {
echo "<tr>";
echo "<td>".$row[0]."</td>";
echo "<td>".$row[1]."</td>";
echo "<td>".$row[2]."</td>";
echo "</tr>";
}
echo "</table>";
}
else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
mysqli_free_result($result);
// close connection
mysqli_close($connection);
?>
</body>
</html>
As you can see, this looks a lot like the code written for
ext/mysql. The only real difference – at least to the naked eye
- is the fact that function names now begin with mysqli_* instead of mysql_*.
Of course, there are a whole bunch of differences under the hood:
ext/mysqli is faster, more secure and more powerful than regular
ext/mysql, and also includes support for prepared statements,
bound result sets, multiple simultaneous queries, transactions and a whole
bunch of other cool stuff.
You can also use ext/mysqli in an object-oriented way,
where each task – connecting, querying, fetching – is actually a method
of the mysqli() object:
<html>
<head>
<basefont face="Arial">
</head>
<body>
<?php
// set server access variables
$host = "localhost";
$user = "test";
$pass = "test";
$db = "testdb";
// create mysqli object
// open connection
$mysqli = new mysqli($host, $user, $pass, $db);
// check for connection errors
if (mysqli_connect_errno()) {
die("Unable to connect!");
}
// create query
$query = "SELECT * FROM symbols";
// execute query
if ($result = $mysqli->query($query)) {
// see if any rows were returned
if ($result->num_rows > 0) {
// yes
// print them one after another
echo "<table cellpadding=10 border=1>";
while($row = $result->fetch_array()) {
echo "<tr>";
echo "<td>".$row[0]."</td>";
echo "<td>".$row[1]."</td>";
echo "<td>".$row[2]."</td>";
echo "</tr>";
}
echo "</table>";
}
else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
$result->close();
}
else {
// print error message
echo "Error in query: $query. ".$mysqli->error;
}
// close connection
$mysqli->close();
?>
</body>
</html>
Here, the new keyword is used to instantiate an object of class
mysqli, and pass the object constructor connection information
(including the database name). The resulting object, stored in the variable
$mysqli, then exposes methods and properties to perform the
tasks of querying, fetching and processing rows, and handling errors.
If you look closely at the two scripts above, you’ll notice the numerous
similarities between the function and method names, and the structure of
the script. Of the two, though, the object-oriented method is recommended,
especially in light of the new object model in PHP 5.
A couple of other important differences to keep in mind:
- With
ext/mysqli, you can include the database name in the
arguments passed to themysqli_connect()function or to the
mysqli()constructor. - When calling
mysqli_query()or themysqli
object’squery()method, the link identifier is mandatory,
not optional.
PHP 101 (part 8): Databases and Other Animals – Part 2
Copyright Melonfire, 2004 (http://www.melonfire.com).
All rights reserved.


37 comments to “PHP 101 (part 8): Databases and Other Animals – Part 1”
May 17th, 2007 at 2:03 pm
Please remove "or the mysqli object’s query() method, " from the last statement as it doesn’t make sense. The "mysqli" object is already attached to a connection.
June 5th, 2007 at 12:01 pm
I am an elementary stage beginner. Someone installed Mysql and PHP for me. Sure, I find the tutorial very helpful. But now I have a problem. I tried to run the script under ‘Hello Database’ but only received on my browser window this message :
Fatal error: Call to undefined function mysql_connect() in c:Inetpubwwwrootdatabase.php on line 19.
What am I doing wrongly?
June 5th, 2007 at 12:11 pm
I am an elementary stage beginner. Someone installed Mysql and PHP for me. Sure, I find the tutorial very helpful. But now I have a problem. I tried to run the script under ‘Hello Database’ but only received on my browser window this message :
Fatal error: Call to undefined function mysql_connect() in c:Inetpubwwwrootdatabase.php on line 19.
What am I doing wrongly?
June 6th, 2007 at 8:36 pm
I just want to stop to say "Thanks for the great tut!" before continuing with part 8.
June 9th, 2007 at 2:55 am
On my machine i had to use a different syntax for the command line. i removed all the ”””s from the outside the ()’s, in other words
CREATE TABLE `symbols` (
`id` int(11) NOT NULL auto_increment,
became
CREATE TABLE symbols (
id int(11) NOT NULL auto_increment,
and
INSERT INTO `symbols` VALUES (1, ‘America’, ‘eagle’);
became
INSERT INTO symbols VALUES (1, ‘America’, ‘eagle’);
with this change it worked fine. Hope this helps someone. Love the tutorial.
August 16th, 2007 at 8:26 pm
I set everything up as stated in the tutorial and attempted to run the code from Hello Database. I received the following output:
"; while($row = mysql_fetch_row($result)) { echo ""; echo "".$row[0].""; echo "" . $row[1].""; echo "".$row[2].""; echo ""; } echo ""; } else { // no // print status message echo "No rows found!"; } // free result set memory mysql_free_result($result); // close connection mysql_close($connection); ?>
I can’t for the life of me figure out why the first echo command is causing the rest of the php code to echo rather than perform the while command and move on.
any ideas?
November 5th, 2007 at 12:40 pm
This tutorial is really confusing. You make a table without first connecting to it? I’ve tried all the code here and all i get are errors.
Surely you connect to the database *then* make the table *then* add things.
November 17th, 2007 at 8:50 pm
Don’t be confused
If you go back and read the first part more carefully, you’ll see that the table at the beginning is there to get you used to working with the mysql client *without PHP*. It’s just more useful to know how the thing works ‘in the raw’ before you start connecting to it from a script.
November 17th, 2007 at 8:52 pm
The reason "" doesn’t work is that those aren’t supposed to be quotation marks, but backticks…
November 17th, 2007 at 8:56 pm
That error message means that ext/mysql isn’t enabled in your setup.
December 12th, 2007 at 3:28 pm
Hello,
I got the same outcome as Stowt and I could not find any answer to it. What’s wrong? Could you help me please?
"; while($row = mysql_fetch_row($result)) { echo ""; echo "".$row[0].""; echo "" . $row[1].""; echo "".$row[2].""; echo ""; } echo ""; } else { // no // print status message echo "No rows found!"; } // free result set memory mysql_free_result($result); // close connection mysql_close($connection); ?>
rod
Ps: so far this tutorial has been very helpful to me. Thank you.
December 19th, 2007 at 2:25 pm
Hi, I’m having the same problem as Stowt and Rodgeck:
"; while($row = mysql_fetch_row($result)) { echo ""; echo "".$row[0].""; echo "" . $row[1].""; echo "".$row[2].""; echo ""; } echo ""; } else { // no // print status message echo "No rows found!"; } // free result set memory mysql_free_result($result); // close connection mysql_close($connection); ?>
Does it have anything to do with the PHP version? I’m using 5.0.41
How can I resolve this?? Please help…
Other than that this tutorial is great.
January 28th, 2008 at 8:55 pm
Hi,
This is maybe the 10th tutorial I’ve tried in an attempt to accomplish the same task: adding info to my database/selecting and viewing that data on my site.
I can output basic PHP functions, so I know that works. I also have a Phorum (PHP/MySQL based) message board on my site that interacts with my mySQL DB, so I know that’s working as well.
But these tutorials always give me the same output – a blank page. Any idea what’s happening?
Thanks,
Sarah
February 27th, 2008 at 1:16 pm
Sarah
I had this problem while I was experimenting with connection scripts unrelated to this tutorial.
I found I got a blank page if the database username of password was wrong.
hope that helps
March 13th, 2008 at 6:45 pm
I couldn’t get the very first exercise above, the creation of the first database in MySQL above, to work.
Here is the error message (note that I wrap everything here relating to input code and output, including error messages, with curly brackets):
{Parse error: syntax error, unexpected T_STRING in C:\wamp\www\Tutorial\Part8 (MySQL & Other Databases)\create_database.php on line 6}
And here is the line 6 referred to above: {CREATE DATABASE testdb;}
I also followed the suggestion of rbstimers and eliminated the "back ticks" (the gizmos that look like left-side single quotes, or single "back" quotes if we are comparing these symbols to back- and forward slashes), although rbstimers’ verbalized instructions do not unambiguously correspond to what he actually does, which causes some confusion because one is not quite sure just how thorough one should be with the hatchet (rbstimers says that he removed all of the back ticks which lie "outside the ()’s", which is difficult to interpret, since these parentheses are concatenated, while in practice – in the example that rbstimers gives – rbstimers also removes the back ticks that are inside the outside parentheses, but outside the inside parentheses, i.e., where concatenation occurs); following rbstimers’ example, I ended up removing all of the back ticks except for the ones enclosing the example of {id} immediately following the code {PRIMARY KEY} (with the "create database" code line above as line 6, and with no empty/blank lines in the code (see the entire page of unedited code below), the "primary key" code line would thus correspond to line 11).
Anyways, it didn’t work, also not with either of the two logical variants (not removing the back ticks located inside the outside parentheses but outside the inside parentheses, while removing those located outside the non-concatenated parentheses, and then reversing this procedure), and of course I wrapped the given code with the usual PHP start/end tags and then the usual HTML start/end tags. It just didn’t work. I confess that I may not have been on the same page as rbstimers, since the language rbstimers uses (he refers to using "the command line") suggests that he was using a DOS setup.
In fact this inspired me to access MySQL on my wampserver2 application (accessed from the system tray), in the belief that the creation of the database might need to take place from there, and MySQL in wampserver2 turned out to be a DOS environment all right, but I couldn’t even open it because every time I plugged in the demanded password (I used the password I use to gain access to phpMyAdmin in wampserver2), it gave a loud beep and closed itself. I also created a different user ID as part of the setup of wampserver2 which may have been the ID used to access databases (a second layer of security in wampserver2?), but when I plug that ID’s password (I log onto phpMyAdmin with the second user ID) into MySQL\MySQL console, the same loud beep occurs and the DOS window closes. This may of course be a simple problem of how priveleges (the ability to access and therefore edit) are set up in wampserver2.
I therefore urge anyone who uses wampserver2, which has built-in everything (MySQL, etc.), according to my understanding, and who has managed to get this code to work, to – in the spirit of Master Vikram – "spill the beans" (tell us others what he/she did to make it work).
I will also say that I am just a little bit disappointed with Master Vikram because up to this point we have only dealt with simplistic stuff, and now when we tackle the first really thorny – and very important – issue, the instructions not only seem to be lacking, there is no effort to repair this shortcoming by providing explanatory "support" here in the Comments. I let this criticism cross the lips of my keyboard
because something tells me that it should not be necessary to create a database from within a special interface of my wampserver2 – I mean, the whole point of cleverly creating databases with the help of PHP, and with the additional help of the language of SQL, is that it can be done (read: should be possible) in PHP 5 and on a normal windows interface, rather than having to do this in SQL alone, or in another arcane database language, and via DOS.
Of course, there is also still the possibility that in my particular wampserver2 case, this has something to do with the way that wampserver2 has to be set up. That second user ID may need to be accessed before one can use the normal localhost windows interface in order to create databases, i.e., still a problem with "privileges". If anybody has concrete info on this problem pertaining to wampserver2 (no speculation, please, and no confusing contributions from those unfamiliar with wampserver2), then please, in the spirit of Master Vikram, do jump in!
The whole unedited nine yards:
(HTML)
(HEAD) (/HEAD)
(BODY)
(?php)
// PHP 5
CREATE DATABASE testdb;
CREATE TABLE `symbols` (
`id` int(11) NOT NULL auto_increment,
`country` varchar(255) NOT NULL default ”,
`animal` varchar(255) NOT NULL default ”,
PRIMARY KEY (`id`)
) TYPE=MyISAM;
INSERT INTO `symbols` VALUES (1, ‘America’, ‘eagle’);
INSERT INTO `symbols` VALUES (2, ‘China’, ‘dragon’);
INSERT INTO `symbols` VALUES (3, ‘England’, ‘lion’);
INSERT INTO `symbols` VALUES (4, ‘India’, ‘tiger’);
INSERT INTO `symbols` VALUES (5, ‘Australia’, ‘kangaroo’);
INSERT INTO `symbols` VALUES (6, ‘Norway’, ‘elk’);
?)
(/BODY)
(/HTML)
Yours,
phileasphogg
March 13th, 2008 at 10:31 pm
I may have been a bit hasty in that criticism above – I should have read the exercise through thoroughly before wailing. I have actually progressed some, among other things I realize that the reference to the "command line" is indeed the command line from within some other interface than the localhost one (I got a bit of traction simply using phpMyAdmin, then accessing the database in question, then creating first a "symbols" table by simple hand operations, then a "symbols2" table using Vikram’s code (but changing the table name from "symbols" to "symbols2", since an earlier error report informed me that the "symbols" table already existed). I have yet to be able to get any output, but that will probably be rectified as soon as I read up on Vikram’s/Melonfire’s "Spealing SQL" tutorial. My apologies, Master Vikram!
phileasphogg
March 15th, 2008 at 9:11 pm
I’m sure a lot of yous have seen the above error generated when you tried to create a table in PHP/MySQL from within your text editor. I just can’t figure out what I am doing wrong, and believe me, I h a v e experimented! I think that the syntax problem (the code in a jiffy) has to do with the fact that MySQL adds a column of numbers/integers (i.e., it numbers each row entry), and maybe this gets in the way when one specifies the contents of a table row to be inserted into the table (I create the table first, then in a separate PHP file, I bring up the database/table up and then add the contents).
I have tried not mentioning at all the variables in that table (call it "twinkies" here), i.e., I sometimes just write "INSERT INTO twinkies VALUES(‘blah’, ‘blah’, ‘blah’)", and I have tried to mention all of the variables like so: "INSERT INTO twinkies(*) VALUES(‘blah’, ‘blah’, ‘blah’)", and then like so: "INSERT INTO twinkies(halb, halb, halb) VALUES(‘blah’, ‘blah’, ‘blah’)". Still I get the error message above! I have also tried adding the friggin numbers like Vikram does above, like so: "INSERT INTO twinkies VALUES(1, ‘blah’, ‘blah’, ‘blah’)", and here I get a message about duplicate keys, presumably because the system is trying to remind me that it can count, that I needn’t list the numbers.
Here is the offensive code:
\<HTML\>
\<HEAD\>\</HEAD\>
\<BODY\>
\<?php
// set database server access variables:
$host = "localhost";
$user = "BruiserHeHe";
$pass = "MeHeHeHeHe";
$db = "testdb";
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
// Insert a row of information into the table "twinkies"
mysql_query("INSERT INTO twinkies
(Name, Region, Population) VALUES (‘Afghanistan’, ‘Asia’, ’26000000′) ")
or die(mysql_error());
mysql_query("INSERT INTO twinkies
(Name, Region, Population) VALUES (‘Albania’, ‘Europe’, ’3200000′) ")
or die(mysql_error());
mysql_query("INSERT INTO twinkies
(Name, Region, Population) VALUES (‘Algeria’, ‘Middle East’, ’32900000′) ")
or die(mysql_error());
etc., etc,
mysql_query("INSERT INTO twinkies
(Name, Region, Population) VALUES (‘Zimbabwe’, ‘Africa’, ’12900000′) ")
or die(mysql_error());
?\>
\</BODY\>
\</HTML\>
I hope somebody can respond to this, but please remember to speak slowly and enunciate your words carefully
.
phileasphogg
March 16th, 2008 at 9:36 pm
I’m kinda talking to myself here (it is the weekend and geeks are screwing around with other things), but hopefully it will be useful to other noobs like me. I found the solution to my problem on a site that I will refer you to in a jiffy. The problem and solution, in a nutshell, is that beginnger do not specify enough columns and that the all-important "id" column is not specified correctly.
Here is how to do it properly (note the addition of the variable "id" in the twinkies variables list and the corresponding "”" in the VALUES array):
mysql_query("INSERT INTO twinkies
(id, Name, Region, Population) VALUES(”, ‘Afghanistan’, ‘Asia’, ’26000000′) ")
or die(mysql_error());
and here is how I did it IMproperly :
// Insert a row of information into the table "twinkies"
mysql_query("INSERT INTO twinkies
(Name, Region, Population) VALUES (‘Afghanistan’, ‘Asia’, ’26000000′) ")
or die(mysql_error());
Note also that if you make one single mistake – a missing comma or single quote is enough! – the error report will tell you that there is a column match problem at row one, which may cause you to wrack your brain in vain to find the problem on line one/row one (some day MySQL will develop intelligent error reporting, such that problems will be accurately identified/pinpointed, but we are where we are, right?). This is especially relevant if you have a long data list (mine consisted of 193 entries). With such a long data list, locating errors can be daunting. The solution is to INSERT the data in smaller increments (all "A"s, all "B"s, etc.), then when a snag arises it is a heckuva lot easier to spot the mistake.
Also, please note that if you run your table creation file more than once, then when you ask the data to spit out a listing or a table, you can get multiple entries (although I had only 193 entries, my first table had 875 entries!!!!). The solution, if you have been experimenting and may have run the creation file more than once, is to of course go into the MySQL database in question and ask it to drop the table in question, then run the creation file once, the insert file once, then run your output file and you will not have any duplicated entries.
Finally, here is the link I found that fixed the problem – hang in there noobs!:
http://htmlfixit.com/cgi-tutes/tutorial_MySQL_Error_Invalid_Query_Column_Count_Does_Not_Match_Value_Count.php
phileasphogg
March 16th, 2008 at 9:41 pm
I just wrote:
"Here is how to do it properly (note the addition of the variable "id" in the twinkies variables list and the corresponding "”" in the VALUES array):"
Make that {id} and {”} in the above (the font here renders both single and double quotes the same!).
Hang in there noobs!
March 20th, 2008 at 4:40 pm
I would like to thank the author first for his excellent tutorial…
THIS IS A SMALL TIP FOR BEGINNERS ONLY!…
Check your MySQL Version First… i use mysql 5.0 in winXP!
i’ll tackle this step by step!
1. CREATE DATABASE database_name; (ex. CREATE DATABASE testdb;)
Note: don’t forget (;)semi-colon!
2. USE database_name (ex. USE testdb;)
Note: again… DON’T YOU EVER FORGET (;)semi-colon!
3. Now CREATE TABLE table_name (ex. CREATE TABLE symbols)
4. Next, include this part like what this tutorial(zend) says…….
(
id int(11) NOT NULL auto_increment,
country varchar(255) NOT NULL default ”,
animal varchar(255) NOT NULL default ”,
PRIMARY KEY (id)
) TYPE=MyISAM;
hey… do u figure out something?
hehehe…
I REMOVED THE (“)backticks
5. then insert data’s in the table:
INSERT INTO symbols VALUES (1, ‘America’, ‘eagle’);
INSERT INTO symbols VALUES (2, ‘China’, ‘dragon’);
INSERT INTO symbols VALUES (3, ‘England’, ‘lion’);
INSERT INTO symbols VALUES (4, ‘India’, ‘tiger’);
INSERT INTO symbols VALUES (5, ‘Australia’, ‘kangaroo’);
INSERT INTO symbols VALUES (6, ‘Norway’, ‘elk’);
Note: i have removed again the (“) backtikcs in table_name(symbols)
6. and the LAST PART is testint the table if it’s working!
i have used the command:
select * from symbols;
7. that’s all folks!
8. this is the outcome of mine!
+—-+———–+———-+
| id | country | animal |
+—-+———–+———-+
| 1 | America | eagle |
| 2 | China | dragon |
| 3 | England | lion |
| 4 | India | tiger |
| 5 | Australia | kangaroo |
| 6 | Norway | elk |
+—-+———–+———-+
6 rows in set (0.00 sec)
9. hope this works to you too!
March 20th, 2008 at 10:45 pm
——-THIS IS THE ERROR MESSAGE ———
Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘test’@'localhost’ (using password: YES) in C:\Program Files\Apache Group\Apache2\htdocs\sqltutorial.php on line 17
Unable to connect!
—— i get this error when i try this tutorial ——–
<html>
<head>
<basefont face="Arial">
</head>
<body>
<?php
// set database server access variables:
$host = "localhost";
$user = "test";
$pass = "test";
$db = "testdb";
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
// create query
$query = "SELECT * FROM symbols";
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// print them one after another
echo "<table cellpadding=10 border=1>";
while($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>".$row[0]."</td>";
echo "<td>" . $row[1]."</td>";
echo "<td>".$row[2]."</td>";
echo "</tr>";
}
echo "</table>";
}
else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
mysql_free_result($result);
// close connection
mysql_close($connection);
?>
</body>
</html>
——- WHAT SHALL I DO? ———-
KINDLY ANSWER THIS ONE PLEASE…. AND MAKE IT CLEAR WHY DO I GET THIS ERROR PLEASE!
THANKS A LOT!
March 21st, 2008 at 7:54 pm
just put available things right after equal sign, i mean instead default things put your data
March 31st, 2008 at 2:48 am
NOW I FIGURED IT OUT!
it was pretty much fine! and working!
thanks…. excellent tutorial!
April 3rd, 2008 at 9:11 pm
Just in case you’re on a Mac and having the same problem I was.
Mysql through the terminal using command/path.
/Applications/MAMP/Library/bin/mysql -v
April 4th, 2008 at 7:15 am
Oops, spoke too soon. This is the one that allowed me to create a database…
sudo /Applications/MAMP/Library/bin/mysql -uroot -proot
April 11th, 2008 at 9:48 pm
i followed the instructions, but got this warning
Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘test’@'localhost’ (using password: YES) in C:\xampp\htdocs\mysqltest.php on line 16
Unable to connect!
i saw the reply to put in your own information, but i downloaded xampp i never had to sign up or register for the mysql database, so how can i put in a password? user name? not possible if i never had one, and apparerntly the "test" default doesn’t work, am i doing something wrong? i know i’ve got mysql on my computer but if i can’t access it, then it’s not going to do me a lot of good, can you help me? i would appreciate any help, thank you
April 24th, 2008 at 8:10 pm
Quote ("i saw the reply to put in your own information, but i downloaded xampp i never had to sign up or register for the mysql database, so how can i put in a password? user name? not possible if i never had one, and apparerntly the "test" default doesn’t work, am i doing something wrong? i know i’ve got mysql on my computer but if i can’t access it, then it’s not going to do me a lot of good, can you help me? i would appreciate any help, thank you")
Answer:
You need to make sure if you have an access to your MySQL database.
If you have an access to the database, then you can proceed like this:
1. On your command line prompt, type : "mysql -u root -p"
2. Then enter your MySQL password in there.
3. You will go directly to "mysql>" command line prompt
4. Type "CREATE DATABASE testdb;" (remember to put semicolon ";" at the end of ALL your statements)
5. Type "USE testdb;"
6. Then, you start to type ALL of this into your "mysql>" command line:
<code>
CREATE TABLE `symbols` (
`id` int(11) NOT NULL auto_increment,
`country` varchar(255) NOT NULL default ”,
`animal` varchar(255) NOT NULL default ”,
PRIMARY KEY (`id`)
) TYPE=MyISAM;
INSERT INTO `symbols` VALUES (1, ‘America’, ‘eagle’);
INSERT INTO `symbols` VALUES (2, ‘China’, ‘dragon’);
INSERT INTO `symbols` VALUES (3, ‘England’, ‘lion’);
INSERT INTO `symbols` VALUES (4, ‘India’, ‘tiger’);
INSERT INTO `symbols` VALUES (5, ‘Australia’, ‘kangaroo’);
INSERT INTO `symbols` VALUES (6, ‘Norway’, ‘elk’);
</code>
7. After that, you need to justify your "database server access variables":
$host = "xxxxxxxx"; // you need to put localhost if you host MySQL on your harddrive, but if you host it on another network, you need to specify the IP address
$user = "xxxxxxxx"; // your MySQL username
$pass = "xxxxxxxxxxx"; // your MySQL password
$db = "testdb"; // this is the database name
8. Then, try to run this. Usually if "Access Denied" happens, you do not have any access or any privileges to the database.
HTH
May 29th, 2008 at 5:48 pm
August 18th, 2008 at 7:37 am
If you are getting the access denied for user ‘test’@'localhost’ error, or if you forgot your sql username/password for some reason, you can simply use this sql command to add the test user to the testdb:
GRANT ALL ON testdb.* TO ‘test’@'localhost’ IDENTIFIED BY ‘test’;
September 19th, 2008 at 3:32 pm
There is a clear problem with the while loop that you are using. It is randomly omitting one row of data, and It does it both on my while loop and even in your tutorial while loop omits row #2 China. What is going on with that weird line. Every other line shows perfectly but not that one.
Chuck
cjrussell@twentyseconddev.com
September 23rd, 2008 at 9:55 pm
I ran acrost this problem when I saved my file as a .html . Simply rename your file to a .php to fix this!
P.s. Best coding tut seris I have ever read! Thanks Vikram!
October 21st, 2008 at 11:39 pm
I’m running locally through MAMP and was able to create the intial table in phpMyAdmin by 1st creating the testdb then copying the SQL data in manually line for line. I also had to create the test user and grant all privileges.
Great tutorials Vikram!!!
- Matt
February 6th, 2009 at 7:50 pm
It all worked fine until I reached the following line:
INSERT INTO symbols VALUES (1, ‘America’, ‘eagle’);
and I got an error message:
ERROR 1146 (42S02): Table ‘world.symbols’ doesn’t exist
Could anyone please help me with this?
Thanks,
February 6th, 2009 at 11:53 pm
This is actually kind of the first programming language I learned, and I really enjoyed the tutorials.
I tried the hello database code with the following lines changed:
$host = "localhost";
$user = "root";
$pass = "12345";
$db = "whatever";
but I got the message, Unable to select database!
I have no idea how to fix this problem.
Thanks for all your help in advance!
March 20th, 2009 at 12:33 pm
mysqli – how does $result->mysqli->query($query) allow $result to become and object and act like an objec as in
$result->num_rows > 0
that means $result is an object using
a method num_rows
please see further details:
Please look at the section below, pertains to the last section in this article, I have also included beginning text and some lines from the code that I have a question
"You can also use ext/mysqli in an object-oriented way, where each task – connecting, querying, fetching – is actually a method of the mysqli() object:
// execute query
if ($result = $mysqli->query($query)) {
// see if any rows were returned
if ($result->num_rows > 0) {
// yes
// print them one after another
echo "<table cellpadding=10 border=1>";
while($row = $result->fetch_array()) {
echo "<tr>";
echo "<td>".$row[0]."</td>";
echo "<td>".$row[1]."</td>";
echo "<td>".$row[2]."</td>";
echo "</tr>";
}
echo "</table>"; "
at the beginning of the code segment above
($result = $mysqli->query($query)) does $result become an object as well
a few down below that there is another line that is
while($row = $result->fetch_array())
in the line above the syntac $result->fetch_array() means
$result is an object , is it?
if so how did it become an object since it is trying to
use the fetch_array() method of the class/object mysqli
I AM VERY CONFUSED AND STUCK AT THIS POINT
BECAUSE I CAN’T UNDERSTAND how this is working.
Can someone please help. I desparately need help with this one.
Perhaps I missed something when i was reading the 2 articles
about classes, I have read them again and again.
But still can determine how the variable $return is useing the
methods/functions within the class /object $mysqli.
June 25th, 2009 at 10:14 am
hello,
thanks for that useful code but i have one query about that code as follows
– How to add 1 column with submit button to every row of table of that retrived data???
September 28th, 2010 at 1:17 pm
Everyone getting…
"; while($row = mysql_fetch_row($result)) { echo ""; echo "".$row[0].""; echo "" . $row[1].""; echo "".$row[2].""; echo ""; } echo ""; } else { // no // print status message echo "No rows found!"; } // free result set memory mysql_free_result($result); // close connection mysql_close($connection); ?>
or similar, you need a .php extention, not .html