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.

PHP functions to create record set.

Mainly four php function are there to create record set.

mysql_fetch_row()
Return record set as an numeric array.

Mysql_fetch_assoc()
Return record set as an associative array.

mysql_fetch_array()
Return record set as an associative array and numeric array.

mysql_fetch_object()
Return record set as an object.

Example 5:- PHP Script to get record from database by mysql_fetch_row()

<?php
$conn=mysql_connect('localhost','root','');
if(!$conn)
die('Not connected');
$database=mysql_select_db('newportal',$conn);
if(!$database)
die('Database Not connected');
$query="SELECT * FROM new_story";
$data=mysql_query($query);
while($result=mysql_fetch_row($data))
{
echo $result[0]."<br>";
}
?>

Code Explain:-
1. connectivity with mysql database.
2. connectivity with database
3. write mysql query.
4. and excute query by mysql_query() function.
5. Then By loop(like while loop) use php function to get from records. Like here we use mysql_fetch_row()
6. by echo statement print records.

Other PHP Function for get records from DataBase.

Here we discuss only concepts.

mysql_fetch_assoc()
while($result=mysql_fetch_assoc($data))
{
echo $result['cat_id']."<br>";
}

mysql_fetch_array()
while($result=mysql_fetch_array($data))
{
echo $result['cat_id']."<br>";
}

mysql_fetch_object()
while($result=mysql_fetch_object($data))
{
echo $result->cat_id."<br>";
}

Example 6:- Get Data from Mysql DataBase(View Data in Table)

<?php
$conn=mysql_connect('localhost','root','');
if(!$conn)
die('Not connected');

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

$query="SELECT * FROM new_story";
$data=mysql_query($query);
echo "<table border='1'>";
echo "<tr>";
while($result=mysql_fetch_array($data))
{
echo "<td>$result[1]</td>";
}
echo "</tr>";
echo "</table>";
?>


Previous
Next