How to execute sql query statement in PHP

We have learn how to create connection and select database in PHP, now i will show how to run query in php.

we will use "mysqli_query" or "mysql_query " method to run the query in php.
Assume we already have connection and already select the database in PHP, here is a example to run the query statement.

NOTE : Refer both post above to create connection and select database

The Database Table

CREATE TABLE IF NOT EXISTS `users` (
  `userid` varchar(40) NOT NULL,
  `password` varchar(80) NOT NULL,
  `ROLES` varchar(40) NOT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`userid`, `password`, `ROLES`) VALUES
('developersnote', 'P@ssw0rd', 'ADMIN');


The code

<?php

require_once('DbUtility.php');
$dbClass = new DbUtility();
$db = $dbClass->getDbConnectionMySQLi();

if (mysqli_connect_errno($db)) {
    $error = '<p><br />Failed to Connect to Database' . mysqli_connect_error();
} else {
    $dbClass->setDatabaseMySQLi($db);
    $strsql = "SELECT * FROM users where userid='developersnote' AND password='P@ssw0rd'";
    $dbComm = mysqli_query($db, $strsql);
    $num_rows = mysqli_num_rows($dbComm);
    if ($num_rows > 0) {
        session_start();
        $row = mysqli_fetch_array($dbComm);
        $_SESSION["LOGINID"] = 'developersnote';
        $_SESSION["ROLES"] = $row["ROLES"]; //read value from column ROLES in query result
       
        //header("Location: ../secure/defaultPage.php"); //redirect to default page..but i will echo successful message
        echo 'Successful';
    } else {
        echo "Is Either Username or password was wrongly entered : " . mysqli_error($db);
    }
}
?>



By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

Popular posts from this blog

How to create zip file to download in JSP- Servlet

How to create DataGrid or GridView in JSP - Servlet

Pinging in ASP.NET Example