MySQL Select Statement using PHP with Source Code | by JOKEN VILLANUEVA | Oct, 2024
MySQL Select statement is used in Selecting one or more records in MySQL database, the SELECT statement is being used.
Syntax:
SELECT * from tableName;
or
SELECT column1,column2 from tableName;
The asterisks(*) symbol in our first example syntax represent all column in the database table.
In the second example, we specify the column name of a table.
$server = "localhost";
$username = "root";
$password = "";
$database = "mysqltuts";
// Create connection
$conn = mysqli_connect(server, username, password, database);
// Check connection
if (!conn) {
die("Connection failed: " . mysqli_connect_error());
}
";
?>
We just simply Select the Last name, First Name and Address of a person from our table, then we execute the query and store the results to the “$result” variable.
Next, using the num_rows function check if the result is greater than zero.
And if the result is greater than zero, the fetch_assoc() function will store the result into an associative array so that we will be able to loop through the records.
The While Loop Loops through the result set and display the result inside the table data because we use table to display the result.
$server = "localhost";
$username = "root";
$password = "";
$database = "mysqltuts";
// Create connection
$conn = mysqli_connect(server, username, password, database);
// Check connection
if (conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to Insert record table
$sql = "SELECT `LNAME`, `FNAME`, `ADDRESS` from `tblpeople`";
$results = mysqli_query(conn , sql);
echo "
";
?>
LAST NAME
FIRST NAME
ADDRESS
$row["ADDRESS"] . "}
} else {
echo "0 results";
}
?>
mysqli_close($conn);
?>
$sql = "SELECT `LNAME`, `FNAME`, `ADDRESS` from `tblpeople`";
$query = conn->prepare( sql );
$query->execute();
$results = query->fetchAll( PDO::FETCH_ASSOC );
?>
foreach( results as $row ){
echo "";
}
conn = null;
echo "
LAST NAME
FIRST NAME
ADDRESS
" $row["LNAME"]. "
" $row["FNAME"]. "
" $row["ADDRESS"]. "
";
?>
📌Here’s the complete source code:
If you find this article valuable, please consider leaving a comment below and share your thoughts.
Your feedback will not only helps us to improve our content but also benefits others in the community by providing diverse insights and experiences.
Thank you for being a part of the Itsourcecode community!
Before you leave, please consider the following:
I would appreciate it if you could show your support by clapping 50 times and following the author.
Follow us on [Facebook]
Visit our other platform [SourceCodeHero]