i

PHP Tutorial

MySQL Commands-Selecting The Data

You have two options to select or view data in SQL. You can either select all the columns or select only required columns to see the data. For both the options you need to use SELECT statement. To view the data use below syntax.

SELECT column1, column2,… from table_name

or

SELECT * from table_name //To select all the columns

You can use the SELECT command in php as below:

$server_name = "localhost";
$username = "username";
$password = "password";
$db_name = "my_project";

$conn = new mysqli($server_name, $username, $password, $db_name);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT visitor_id, name, email FROM Visitors";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["visitor_id"]. " - Name: " . $row["name"]. "
" . Email $row["email"]. "
";
    }
} else {
    echo "0 results";
}
$conn->close();
?>

You can also LIMIT the data to choose how many records you want to see. For example, if you want to see only 20 records you can write the below statement.

SELECT * FROM Visitors LIMIT 20;

If you want to see the data for 5 visitors after 20th record then you can use OFFSET as below:

SELECT * FROM Visitors LIMIT 5 OFFSET 20;