Sunday, 6 March 2016

Reading PHP and MySQL a Single Value from a table



When you want to read a single value from a MySQL table following code will help you.

Your need to fetch row using query function with following syntax

     [connection_object]->query(sql statement)

After fetched rows use mysqli_fetch_assoc function for access row by row records
   
    Var_name= mysqli_fetch_assoc([connection_object]->query(SQL Statement))

mysqli_fetch_assoc returns one dimensional array so use can use table column name as index


con=mysqli_connect("localhost","root","","db_name");


$sql="select id from student_table where id='" . $id . "'";


$row = mysqli_fetch_assoc($this->con->query($sql));


echo $row['id'];


Single line statement

$row = mysqli_fetch_assoc($this->con->query("select name from stu where roll=1"));
        echo $row['name'];

Reading all rows from MYSQL table


con=mysqli_connect("localhost","root","","db_name"); 
$sql="select * from table_name";

if($result=$this->con->query($sql))
{
while($r=$result->fetch_assoc())
{
echo $r['col_name1'] ;
                                        echo $r['col_name2'];
}
}