Database operation in PHP

Database operation in PHP

We are using MYSQL Improved extension,a powerful PHP extension design for working with database.We are creating a MySQL database that use mysqli_connect function

$mysqli = mysqli_connect("localhost","username","password","databseName");

We use query method on the $mysqli object

$result = $mysqli->query("SELECT * FROM charactors")

Additionally.We can call a method use this syntax:


Show the Data

The fetch_object method will return each records we got from the database.once at a time.When you out of the records,it return NULL.For example:

$mysqli = mysqli_connect("localhost","root","root","phptest");
$result = $mysqli->query("SELECT * FROM characters");
        <th>First Name</th>
        <th>Last Name</th>
    <?php while ($row = $result->fetch_object()) : ?>
        <td><?php echo $row->id; ?></td>
        <td><?php echo $row->firstName ?></td>
        <td><?php echo $row->lastName ?></td>
        <td><?php echo $row->occupation ?></td>
    <?php endwhile; ?>

Insert Data

At the beginning,we connect the database again.Then creating three variables to hold the data we want to insert to the database.Finally we use the insert query in insert the data in database and show in the table.But you do not use it in the production environment.

$mysqlinsert = new mysqli("localhost","root","root","phptest");
$firstName = "Me";
$lastName = "you";
$occupation = "Nothing";
$result = $mysqlinsert->query("INSERT INTO characters (firstName,lastName,occupation) VALUES ('$firstName','$lastName','$occupation')");