The PHP SELECT statement is used to select data from a MySQLi table.
To select data from one or more tables.
Syntax:
SELECT column_name(s) FROM table_name
To select ALL columns from a table.
Syntax:
SELECT * FROM table_name
PHP mysqli_connect() function:
PHP mysqli_connect() function is used to open a new connection to the MySQL server. If the connection is established this function returns the resource, else it returns a null.
PHP mysqli_query() function:
PHP mysqli_query() function is used to perform a query against the MySQL database.
Syntax:
mysqli_query(connection,query,resultmode);
Connection: This is a required parameter which is used to specify the MySQL connection to use.
Query: This is an optional parameter which is used to specify the query string.
Resultmode: This is an optional parameter which is used to specify a constant either MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT.
MYSQLI_STORE_RESULT is the default value of the resultmode. MYSQLI_USE_RESULT is used when a large amount of data need to be retrieved.
PHP mysqli_num_rows(mysqli_result $result):
The PHP mysqli_num_rows(mysqli_result $result) is used to retrieve number of rows in a table.
PHP mysqli_fetch_assoc(mysqli_result $result):
The PHP mysqli_fetch_assoc(mysqli_result $result) is used to retrieve rows of a table as an associative array. The column name of the table are the key of the array. As the number of rows ends, PHP mysqli_fetch_assoc(mysqli_result $result) function returns a NULL value in the array.
Example:
<!DOCTYPE html> <html> <body> <?php $phpconnect = mysqli_connect("localhost","Ben","Ben_password"); if (mysqli_connect_errno()) { echo "Connection Failed; " . mysqli_connect_error(); } $phpdatabase = "SELECT id, firstname, lastname, email FROM MyFriends"; $result = mysqli_query($phpconnect, $phpdatabase); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]." - Mail_ID: " . $row["email"]. "<br>"; } } else { echo "No results"; } mysqli_close($phpconnect); ?> </body> </html> |
Output:
id: 1 - Name: BEN DICHOSTA - Mail_ID: dichosta@example.com id: 2 - Name: JOHN DEY - Mail_ID: john@example.com id: 3 - Name: FLAIRA GATES - Mail_ID: gates@example.com |