473,386 Members | 1,827 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ


PHP MySQL: Advanced Methods

By Blair Ireland
Senior Editor, TheScripts.com

Grabbing that Data - More Advanced Methods

We will use the following database, which is the same database we have always been using;

mysql> CREATE TABLE info (
> id INT NOT NULL AUTO_INCREMENT,
> name VARCHAR (50),
> email VARCHAR (50),
> opinion VARCHAR (30),
> PRIMARY KEY (id));

This table is rather small, but everything listed here still applies to larger tables.

mysql_fetch_array

The function, mysql_fetch_array, will grab a query result row, and save the contents in an associative array.

The syntax is:

array mysql_fetch_array(int result, int [result_type] );

If there are no rows to return, the result will be false.

This function is quite similar to the function mysql_fetch_row(), but, it is a lot easier to use (in my opinion at least).

Ok, enough blabbering about, its time to show you all what you want to see, how to use it.

<?php

/* declare some relevant variables */
$DBhost = "Your-MySQL-servers-IP-or-domainname";
$DBuser = "your user name";
$DBpass = "Your Password";
$DBName = "The Name of the Database";
$table = "info";

mysql_connect($DBhost,$DBuser,$DBpass) or die("Unable to connect to database");

@mysql_select_db("$DBName") or die("Unable to select database $DBName");

$sqlquery = "SELECT * FROM $table WHERE opinion = 'is great'";

$result = mysql_query($sqlquery);

while($row = mysql_fetch_array($result)) {
echo "<font face=arial size=-1><p><b>Name:</b>".
$row[name] ."<br><b>E-Mail:</b>". $row[email]. "</p>";
}

if(mysql_num_rows($result)<1){
echo "<font face=Arial size=+0><b>No
Results!</b></font><br>";
}

mysql_free_result($result);
?>

Look easier then before? Thats because it is. This array will hold all of the values of this row, and each of them can be found in the associative array, under the name of the corresponding column.

As I stated earlier, this method works quite well, and it doesn't really matter how big your table is, all of the rows contents will be saved safely.

There is a new function listed here though, mysql_free_result. This function helps you relieve the memory that was used during the query. All of the associated result memory for the result you specify will be freed.

mysql_num_rows does play a role in this code though. If your amount of results is less then 1, it will just output that there were no results made during this query. That is better then outputting nothing at all, so you will probably want to use this function in all your future queries.

« Starting Off  

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.