MySQLi Tutorial: Connect, Select, Display, Close.

Here is the table I’ll be using in this example, copy and paste it into your MySQL admin tool, commonly phpMyAdmin:

CREATE TABLE IF NOT EXISTS `people` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `age` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
INSERT INTO `people` (`id`, `name`, `age`) VALUES(1, 'Mike', 26);
INSERT INTO `people` (`id`, `name`, `age`) VALUES(2, 'Joe', 19);
INSERT INTO `people` (`id`, `name`, `age`) VALUES(3, 'Stephanie', 18);
INSERT INTO `people` (`id`, `name`, `age`) VALUES(4, 'Angela', 21);

Ok, lets dive right in, first we’ll need to connect to our database, using mysqli:

<?php
/* so we start by intializing the mysqli class
we will pass our credentials into the class initilization 
the order: host, username, password, database*/
$sql = new mysqli('localhost','username','password','database');
 
/* ok so we've connected, let's write our query, 
we'll set a variable called name */
$name = 'Mike';
$query = $sql->query("SELECT `age` FROM `people` WHERE `name` = '$name'");
$result = $query->fetch_object();
echo "$name is {$result->age} years old.";
 
/* ok we're done, let's close our connection */
$sql->close();
?>

And there we have it, a very simple connect, and display using the mysqli extension in PHP5. If you are coming from the mysql_* procedural functions, MySQLi can take some getting used to, fiddling with simple selects like this should help you get familiar with the syntax of using the class. If you are used to using classes (of your own or pre-made) this should come easily to you.

I hope you found this useful, thanks for reading!

Author: Mike on March 23, 2011
Category: MySQLi, PHP, Tutorials
Tags: , , ,

2 thoughts on “MySQLi Tutorial: Connect, Select, Display, Close.”

  1. Boston says:

    That saves me. Thanks!

Comments are closed.

Last articles