Table creation in PHP
To create a table in PHP, you can use the following steps:
- Establish a database connection using PHP’s
mysqli
orPDO
extension. - Define a SQL query that creates a table. For example, the following code creates a table called “users” with three columns:
CREATE TABLE users ( id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL, password VARCHAR(255) NOT NULL );
Execute the SQL query using the mysqli_query()
or PDO::exec()
function, depending on which extension you are using. Here is an example using the mysqli
extension:
$conn = mysqli_connect("localhost", "username", "password", "database_name");
$sql = "CREATE TABLE users (
id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
password VARCHAR(255) NOT NULL
)";
if (mysqli_query($conn, $sql)) {
echo "Table created successfully.";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
Note that you should always sanitize user input and use prepared statements to prevent SQL injection attacks.
Apply for PHP Certification!
https://www.vskills.in/certification/certified-php-developer