PHP - DATABASE CONNECTIVITY Contd.
Hello All...
welcome every one. I'm going to start PHP lectures for Very Beginners, who
wants to learn PHP from very beginning. No matter if you do not have any basic
programming concept. If you follow my tutorials I hope you will surely get some
how good knowledge of PHP.
Today our
Topic is
PHP-DATABASE
Today we
will learn about how to fetch record from MySQL and display on browser using
SELECT query. As told earlier before performing any action with MySQL you need
connection with MySQL at the top of coding even before of HTML coding.
<?php
$conn =
mysqli_connect(“localhost”, “root”, “”, “school”) OR die(mysqli_connect_error($conn));
?>
After you
have successful connection with MySQL you need to retrieve data from MySQL. How
you will retrieve here is the process.
<?php
$qry = mysqli_query($conn,
"SELECT * FROM students");
if($qry){
while($row =
mysqli_fetch_array($qry)){
echo
$row['student_id'];
echo
$row['student_name'];
echo
$row['student_address'];
}
}
?>
Here is the
simple changing after the query is true. After the query is true we have
started a while loop and inside that while loop we have given a function mysqli_fetch_array()
that will retrieve the information from table and it takes parameter the query
above you have initialized and that is stored in a variable called `row` or
anything you want. Now the record has been retrieved we just need to
echo/display it on browser and to display. Little changing while displaying
record we need to echo column names as defined in MySQL table within the
brackets and single quotations, along with the variable name in which
mysqli_fetch_array is stored. Below is the pictorial view of code and retrieval
of records.
I have used
<br /> tag to more clarify the records otherwise it may be difficult to
understand. Why there has been used While loop not any other because if you
remember in previous lectures of loop that While loop works on basis of
condition, and if there is no records in table and mysqli_fetch_array will
return nothing and 0 will be stored to row variable and 0 means nothing or
false. And if while loop becomes 0 or false it will not work further. Further
DIE function is used in the connection coding that if connection is not
established or not connected properly `OR` statement will be executed, DIE
function is used to stop the execution of code, if there is any error in
connection only error will be shown on browser no remaining code will be
executed not even HTML code.
Thanks Guys.
Any thing missing or any question from this topic you can comment below, I will
be trying to solve and answer your question.
Our topic
continues to `PHP-DATABASE`
Good Luck J
No comments:
Post a Comment