Select Query
How to get data from database?.

For Get data from DataBase Use MySQL select query.

Syntax:-
SELECT field1, field2,...fieldN from table_name1, table_name2...
[WHERE Clause]

Some MySQL Query Example:-

Example 1:-
Select * from emp;
Where emp is table name. and (*)  is use to select all table fields.

Example 2:-
Select emp_id,emp_name_emp_city from emp;
This query will reterive only three columns(emp_id,emp_name,emp_city) from emp table.

Example 3:-
Select * from emp where emp_city=’Delhi’
This query will reterive only those records. Where emp_city columns has Delhi.

Example 4:-
Select * from emp order by emp_name;
This query will display all records  alphabetically(ascending order) by emp_name.

Select Data through PHP & Mysql

<?php
$conn=mysql_connect('localhost','root','');

if(!$conn)
die('Not connected');
$database=mysql_select_db('test',$conn);

if(!$database)
die('Database Not connected');
$query="select * from info";
$data=mysql_query($query);

while($result=mysql_fetch_row($data))
{
echo $result[1]."<br>";
}
?>

Select Data through PHP & Mysqli (Procedural)

<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "test";

$conn = mysqli_connect($server, $username, $password, $database);

if (!$conn) {
die("Mysql not Connected");
}

$query = "select * from info";
$result = mysqli_query($conn, $query);

while($row = mysqli_fetch_assoc($result)) {
echo $row["username"]. " " . $row["email"]. "<br>";
}

mysqli_close($conn);
?>

Select Data through PHP & Mysqli (Object Oriented)

<?php
$server = "localhost";
$username "root";
$password "";
$database = "test";

$conn = new mysqli($server, $username, $password, $database);

if ($conn->connect_error) {
die("Mysql not Connected");
}

$query = "select * from info";
$result = $conn->query($query);

while($row = $result->fetch_assoc()) {
echo $row["username"]. " " . $row["email"]. "<br>";
}

$conn->close();
?>

Select Data through PHP & Mysql (PDO)

<?php
$server "localhost";
$username "root";
$password "";
$database = "test";

try {
$conn = new PDO("mysql:host=$server;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $conn->prepare("select * from info");
$result->execute();
$row=$result->fetchAll();

for($i=0;$i<count($row);$i++){
for($j=0;$j<count($row[$i])/2;$j++)
echo $row[$i][$j]." ";
echo "<br>";

}

}
catch(PDOException $e) {
echo "Error";
}
$conn = null;
?>


Previous
Next