To successfully fetch data from MySQL using mysqli extension in PHP you need to perform more or less three actions: connect, execute prepared statement, fetch data.
Connection:
The connection is really simple. There should always be only 3 lines of code for opening a connection. You enable error reporting, create new instance of mysqli, and set the correct charset.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'user', 'pass', 'db_name');
$mysqli->set_charset('utf8mb4');
Prepared statement
This is the tricky part. You need to prepare SQL statement to be executed. Careful, never concatenate PHP variables into SQL directly. Bind the variables using placeholders. Once the statement is ready you can execute it on the server.
$stmt = $mysqli->prepare('SELECT * FROM teacher WHERE tremail=?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
Fetch the data
If your prepared statement should return some results, you need to fetch them and do something with the records. To fetch the result use get_result()
. This will give you an object that you can iterate on to fetch each row one by one.
$result = $stmt->get_result();
foreach ($result as $row) {
echo $row['user_id'];
}
If you are only starting learning PHP, please consider learning PDO instead. It is easier to use and offers more functionality. Use mysqli only for legacy projects.