MySQL and PHP commands


x-----------x
| MYSQL/PHP |
| COMMANDS |
x-----------x

Okay, this is my very first tutorial... ever. I will be explaining lots of mysql functions in php. Here we go...

MYSQL_FETCH_ARRAY
This is the code lots of people like to use to get information from the database. The code basically goes like this...
PHP Code
  1. <?
  2. $select_info= mysql_query("SELECT * FROM users WHERE userlevel='0' ORDER BY `id` ASC");
  3. // Look for users with a userlevel of 0 and order the results by the users ID ascending
  4.  
  5. $the_users= mysql_fetch_array($select_info); // Get the user so you can select various results.
  6.  
  7. //Okay this is where im a bit rusty since i havnt used fetch arrays before xD
  8.  
  9. echo "$the_users['username']"; //I have no idea if thats correct i think it might be this or...
  10. echo "$the_users[1]";
  11. ?>


The above code will hopefully get a result from the database and put the username of a user on the page.

MYSQL_FETCH_OBJECT
Ahh, my favourite function. This good function is the same as a fetch array but works differently. Take a look at the code below...
PHP Code
  1. <?
  2. $select_info= mysql_query("SELECT * FROM users WHERE userlevel='0' ORDER BY `id` ASC"); //Okay im using the same mysql query from before so you can easily contrast the both.
  3.  
  4. $the_users= mysql_fetch_object($select_info); // The same thing but i changed array to object
  5.  
  6. echo "Hello $the_users->username"; // Okay basically this one is saying Hello (the users Username from the mysql result).
  7. ?>

Okay as you can see, instead of using $the_users['username'] i used $the_users->username. The function, when echoed, works like this: $variable_here->table_row e.g. username

MYSQL_NUM_ROWS
Okay mysql num rows is a descent and useful command used for recording the number of results found from a query. Okay first lets see a table.
Table name: users
------------------------------------------
| Username | Email | Userlevel | Password |
|_________________________________________
| Ilyas | None | 3 | 123123 |
| Killer | k@h.com| 0 | abcabc |
| Namco | None | 0 | qwerty |
|_________________________________________|
Okay now lets get the info.
PHP Code
  1. <?
  2. $select= mysql_query("SELECT * FROM users WHERE userlevel='0'"); // Im sure we dont have to go thru this again :)
  3.  
  4. $number_of_results= mysql_num_rows($select); //Using the mysql num rows function to get the number of results.
  5.  
  6. echo "$number_of_results"; // This will echo the number 2 since there is only 2 users in the table with a userlevel of '0'.
  7. ?>

Notice that the mysql_num_rows function does not need an arrow ( -> ) or a [ blabla ] to work. U just use the variable only.

Okay thats all for now. Until next time.
I may have made mistakes since i rushed it so plz correct me. Thanks
ilyas-shezad's Avatar
Views:
2,465
Rating:
There are currently no comments for this tutorial, login or register to leave one.