2: Run SQL Query
After successful connection, second step is run SQL query.
3: Close connection
After performing required task on database by running SQL query, 3rd
step is to close the connection.
1: How to connect?
Two functions in PHP to connect to database:
mysqli_connect()
mysql_connect() slower one
General form:
mysqli_connect(hostname, username, password, database)
$conn = mysqli_connect("localhost", "root", "", "suit") or
die(“connection Failed);
2: How to Run SQL query
• Example: read all records of a table
$sql=“select * from student”;
Then run following function: general form
mysqli_query(connection, query);
$result=mysqli_query($conn, $sql) or die(“query unsuccessful”);
How to run …….
• The mysqli_fetch_assoc() function in PHP is used:
- to retrieve a single row from a database query result set as an
associative array, where column names serve as keys.
- Each time it's called, it fetches the next row, and it returns NULL
(or FALSE) when there are no more rows available.
This is commonly used in a while loop to process all the rows from a
mysqli_query() result.
How it works:
a) mysqli_query(): first execute a SELECT query using mysqli_query(),
which returns a mysqli_result object containing the data.
b) mysqli_fetch_assoc(): You then pass this result object to
mysqli_fetch_assoc().
How it works…
c) Associative Array: The function returns an associative array where
the keys are the column names from your query and the values are the
corresponding data for that row.
d) Looping: To get all rows, you typically use a while loop that continues
to call mysqli_fetch_assoc() until it returns NULL (or FALSE), indicating
that there are no more rows to fetch.
While loop to read all records
while($row=mysqli_fetch_assoc($result))
{
echo $row['CNO’];
echo $row['Name’];
echo $row['Marks’];
echo $row['domicile];
}
3. Close connection
mysqli_close($conn);